How to use root variables with CSS

Reading time: 1 minute(s)

Do you ever lose track of which hex code represents which number? Keep better track of your number or any other CSS value with root variables.

Root variables should be placed at the top of your stylesheet. They are declared with the following syntax:

:root {
        --darkred:#AA000;
        }

Now, in order to use the variable, put your CSS somewhere underneath:

body a {
        color:var(--darkred);
        }

If you declare root variables in your main stylesheet, you can overwrite all uses of the variable on the current page by including the :root syntax with a matching variable. For example, if on one page you wanted all of your “dark red” variable to change to lime green, you would use the below on the individual page:

:root {
        --darkred:limegreen;
        }
body a {
        color:var(--limegreen);
        }
}

Root variables can be used for colors or any other CSS value such as “50px”.

This can be useful for:

  • keeping track of the colors on your website
  • assigning all of your divs the same padding at once
  • allowing others to customize a creation (such as in my webring guide).

Leave a Comment