Why I Switched to CSS Custom Properties and You Should Too

When sitting down with some of my students to discuss and design our own in house CMS and news application we decided to take the time to really think about every granular detail of our design system. At the same time I was beginning to work on my site's redesign and I was looking at starting from scratch with my design system. Looking around online for some new ideas I came across Scott Tolinksi's CSS Design System course. Personally I am very strong in CSS but greatly preferred the extra horsepower afforded by SCSS and that variable/mix-in system. I was curious, why was someone like Scott Tolinksi not using SCSS and advocating instead for CSS custom properties?

SCSS's variable integration is powerful, easy to use and does my absolute favorite thing in the whole world (convert Hex to RGBA in linear gradients). How could CSS custom properties, AKA CSS variables, compete with that? CSS custom properties have one major advantage over SCSS that SCSS cannot compete with. CSS custom properties are CSS! What I mean by that statement is CSS custom properties, since they are native to CSS, can be used in production code and be read by the browser natively (unless you need to support IE). SCSS variables, while amazing, cannot be parsed by the browser natively and thus need to be compiled down to native CSS. Why does this matter? That was my question until I checked out Modern CSS Design System on LevelUpTutorials.com.

CSS custom properties allow us to really cool things like theming (dark mode, light mode etc) really easily in our application with minimal effort. Since CSS custom properties can be scoped we can simply change the definition of a custom property within a specific class. If we define a property like --background , we can change that definition in our light and dark mode classes. In the example below you can see me beginning to create a theme based on my favorite VSCode theme, Outrun Electric. By redefining the background custom property with a new color (also stored as a custom property) I can easily change my site's theme. I defined background color in the root of my project so I can redefine that property by targeting the body with a new class that changing the root custom property definitions.

.outrun-mode{
        --background: var(--purple);
        --textColor: var(--lightgrey);
    } 


Nuxt makes this even simpler. Nuxt has a wonderful theme switcher plugin that you can use with your custom properties. Even without a framework, adding new themes or improving your workflow with custom properties is a breeze. I made the shift from SCSS variables and I don't intend to go back. Next year I will be adjusting my curriculum to reflect this. That doesn't mean I won't be using SCSS. Mixins, nesting, and breaking up our stylesheets is still really useful so I won't be shifting away from SCSS anytime soon. Give custom properties a shot!