BTemplates Blog

Tutorials, documentation and news about Blogger.

CSS Variables

Versión en Español

CSS Variables are very useful when designing a blog, a website or a web application, but what are CSS variables? They are nothing more than custom properties, but this condition allows you to store data in them and avoid repeating these values in your code.

How to use CSS variables

A common best practice is to define them within the pseudo element :root, so these variables are available in the context of the whole HTML document. To get the value of a variable you use the var() function along with the name of the variable.

Example: Suppose we want our site to have a white main background and a header and footer with gray background. Using variables, the CSS could look like this:

:root {
    --color-background-main: #fff;
    --color-background-secondary: #999;
}

body {
    background-color: var( --color-background-main );
}

header, footer {
    background-color: var( --color-background-secondary );
}

And in general, every time we need to use a white background, we can make use of the variable --color-background-main and if we want to change the color white by black, we would only need to change it once in the variable’s definition.

Note that the name of the variables is case sensitive.

Other uses for CSS variables

The flexibility of these custom properties is very great and allows us to make it much easier to add features such as:

  • A dark mode design option.
  • Create multiple color palettes.
  • A specific design for printing.

Compatibility

Support for custom properties in CSS. Via Mozilla Developers.

CSS variables are already supported by all modern browsers, so unless extensive compatibility is a requirement, it is safe to use them in our production designs.

Conclusion

I must admit that I stopped updating on many of the “new” CSS features and it’s not until now that I’m really taking advantage of many of them. More than a conclusion, a question: Do you use CSS variables in your designs in production?