Using CSS Custom Properties for Better UX

CSS Custom Properties

Last updated - July 8, 2021

CSS3 brought with it one of the biggest additions that the CSS spec has had for a long time. It generated a lot of buzz because it addressed a key issue that had plagued developers for years, and was the main cause people had for preferring the use of pre-processors like SASS: the ability to use variables.

With the addition of CSS variables, a lot of the code that had to be written to support basic features like theming is no longer necessary. It’s a useful feature that can be used to avoid repetition and enable even more use cases like dynamic font sizes and simplicity in the addition of responsiveness in a web app.

Getting rid of clutter with CSS variables

A common feature of most apps is brand colors that need to remain the same and consistent throughout the app. Nobody has the mind to store ten different hex values in their heads for future reference, and going back and forth between files to copy values is not only cumbersome, but it’s also detrimental for productivity. Now, imagine the amount of work that has to be done if those colors need to change.

CSS Custom Properties

Using CSS preprocessors with WordPress is the most common way of dealing with the problem. These offer support for a whole host of features like mixins, nested declarations and, of course, variables, which are a major boost to productivity. 

All you need to do is write your code once and it gets compiled to CSS, which you can freely access and change if you so wish. However, the inability to find and change these values at runtime, to, say, add a dark theme to your web app is their biggest drawback. It’s a major problem not only because SASS doesn’t support it, but it likely never will.

The addition of custom built-in variables to CSS opens has had a major effect on how we write applications, especially with regards to theming and responsive design.

What’s browser support for CSS variables like?

This is the most common question that comes up when CSS variables are brought into a discussion. According to Caniuse, browser support for CSS variables stands at 93.16%. It’s supported in all modern browsers (Chrome 49+, Firefox 31+, Safari 9.3+, Opera 36+ and Edge 16+). As always, IE is missing from the show and has a surprising 6.47% market share. For the poor developers that have to support old browsers, fret not. Polyfills, or more correctly, ponyfills, are here to save the day.

A formal introduction to CSS variables

If you’re familiar with CSS variables, you shouldn’t have any trouble with CSS variables.

SASS variables are declared like so:

<pre>

$facebook-blue: #4267B2;

</pre>

While CSS variables are declared a little differently:

<pre>

:root {

–brand-color: #4267B2;

}

.brand-navbar {

background: var(- -brand-color);

}

</pre>

Notice a few differences between the two syntaxes:

  • CSS variables need to be preceded by two dashes
  • CSS variables are normally declared inside ‘:root’, but can be redeclared at any time. 
  • CSS properties are retrieved using the ‘var()’ function.

CSS variables also offer access to several additional features.

Cascading values

CSS properties cascade following normal cascading rules. In other words, redeclarations below don’t affect those above.

<pre>

:root { –color: yellow; }

div { –color: blue; }

#great { –color: green; }

* { color: var(–color); }

<p>I’ll be yellow, inherited from root!</p>

<div>I’m blue!</div>

    <div id=”great”>

       It worked! I’m green!

    <p>I’m also green! Inherited from above!</p>

    </div>

 </pre>

Fallback values

The ‘var()’ function accepts several parameters. The second can be used as a fallback value in case the custom CSS property is not defined. This is a useful feature for anyone that needs to access the CSS variables via JavaScript.

Its signature looks like ‘var(<custom-property-name> [, <declaration-value> ]?)’ and can be used in the following way

<pre>

    .brand-navbar {

         background: var(–brand-color, “#4267B2”);

     }

</pre>

If ‘–brand-color’ is not defined, “#4267B2” will be used instead,

Access via JavaScript

One of the best reasons to use CSS variables over a preprocessor is the ability to access custom variables via JavaScript. Preprocessor variables don’t live in the browser. They are evaluated when the code is compiled. This way, preprocessor variables cannot be accessed in the browser. With CSS variables, the property lives in the browser, granting the ability to edit values on-the-fly. 

Consider a dashboard that allows the user to select custom colors via a popup or something similar. 

<pre>

    .brand-navbar {

         background: var(–brand-color, “#4267B2”);

     }

    //To get the current value

    getComputedStyle(document.documentElement).getPropertyValue(‘–brand-color’);

   //To set the value

    document.documentElement.style.setProperty(‘–brand-color’, ‘red’);

   //You can even assign one CSS property to another

  document.documentElement.style.setProperty(‘–brand-color’,’var(–secondary-color)’);

</pre>

Global and local scoping

If you’re familiar with JavaScript (or any programming language, really), then you probably understand the concept of scoping. Variables can normally defined such that they are accessible to only certain parts of the code, called the local scope, or made available for use throughout the app, called the global scope. 

CSS Custom Properties

CSS variables work similarly. Some variables should be scoped globally for easier reference, e.g. brand colors and vertical spacing. These usually remain the same throughout the app and in the event of a change, it should be reflected everywhere. In contrast, variables that may require local scoping include buttons with different large and small variants. If you wanted to change the padding on a particular button, you wouldn’t want the changes to traverse the whole DOM. It needs to be changed in just a single point in the app.

By default, CSS properties are locally scoped. And if you’ve worked with either JavaScript or any other programming language, scoping has its own set of issues. Since they can be inherited, they also act like local variables, which can have some interesting repercussions if you’re not careful with how they are used. Since values cascade, you need to be mindful of how you change them, especially when JavaScript is concerned.

Using custom properties with media queries

Just like with preprocessors, a major downside to using CSS properties is that they can’t be used within media queries. For example, this won’t work.

<pre>

    @media (min-width: var(–breakpoint)){

         padding: 1rem;

    }

</pre>

What you can do instead is to redefine custom properties within media queries. If you need to change the font size when the browser scales down, you’re in luck. With CSS variables, you can listen to browser changes using JavaScript and change whatever sizes need to be scaled down just once.

What are some practical applications of custom CSS properties?

“Today, aside from using CDN services to improve site performance, using CSS custom properties is one of the fastest ways to improve productivity,” advises Colby Stuart, a custom paper writing service web designer. 

Apart from well-highlighted benefits, it adds to productivity, are there any real-world examples of how they can be used in a web app?

Adding dark mode

A new trend that has captured the consumer market is the demand for dark mode in all modern software – that includes web apps. It may be a little bit more complicated than adding a dark background color. Other things that need to be considered include how the text colors will change and how images with white backgrounds will be affected.

All this is made possible by first declaring variables throughout your app. When the user triggers the switch to turn the website theme dark, trigger a JavaScript function that changes the CSS variables. If your web app is more complicated, this could also include replacing the current images with dark mode-friendly ones.

Adding Dark mode on WordPress

CSS variables have been so influential that they’ve reached the world of WordPress. Today, creating a dark mode (or, more generally, theming) a WordPress app is fairly trivial. 

CSS Custom Properties

Most WordPress developers rely on the Customizer to change the appearance and functionality of their sites. It provides access to things like colors, fonts, background images and so on by accessing the CSS of your site. The major problem with this is that by changing the CSS this way forces PHP to rerender your HTML, and in doing so, causes the server to resend the whole file to the browser. Your app makes an unnecessary request, consuming more data than it needs to.

“If such an app were a consumer-facing, you’d probably get a lot of complaints. If you don’t have dedicated CSS files for whatever variables you want to change, things get a whole lot worse.” Helena Newman, a senior developer at papersowl review and publisher for resume writing services considers it a necessary addition to the CSS spec. 

Using CSS variables, all the colors are changed in the browser using JavaScript. The only request that’s going to be made is persisting the current theme to the server if it’s necessary. And even then, such a variable can be saved in the browser.

Adding responsive design to a website

With more mobile phones on the internet than ever before, the need for responsive websites has never been more apparent. The most crucial aspect of responsive design that catches developers off their toes is changing font sizes. For an app that uses multiple fonts or dynamic fonts, keeping track of them and changing them for different browsers is a chore.

Instead, custom CSS properties allow you to define a universal font size that can be used and reused throughout your website. In case it needs to change, all you need to do is call a JavaScript function and it all works.

If you don’t need to support ancient browsers, custom CSS variables can be used in conjunction with the (relatively) new grid CSS system to eliminate the need for media queries altogether.

Then again, media queries may still be necessary if you need to listen to width changes within the CSS itself. This is the only way you can support browsers that don’t allow JavaScript to run.

Conclusion

Custom CSS variables are some of the most significant additions to the spec in quite a while. They can simplify your design process by removing clutter from your CSS files and eliminating the need for making any unnecessary additional requests.

LEAVE A REPLY

Please enter your comment!
Please enter your name here