A picture of myself

Atanas Stanilov

Part-time web developer. Full-time superhero.

Shorts: CSS variables

IN: SASS/CSS
Jul 4th 20202 min read

'Shorts' will be quick to read stories on different topics. Today we'll take a quick look at how to use CSS native variables, or also known as custom properties.

Declaring CSS variable

A custom property is defined as starting with -- and preceded by whatever case-sensitive name we like to give to our variable.

element {
    --custom-property-name: 16px;
}

Using variables

To make a use of the declared variable later in our CSS we recall it with the var() function:

div {
    font-size: var(--custom-property-name);
}

The selector, where the variable is defined, becomes the scope of where the variable is available. So, to have global variables accessible everywhere, they can be defined in the :root selector:

:root {
    --primary-color: red;
    --secondary-color: black;
    --base-font-size: 14px;
}

Fallback values

The var() function also provides us with a fallback value, for when the variable we try to access is unavailable(will return invalid value). The fallback value can be provided to the function via a second parameter var(--primary-color-darker, darkred). So if we haven't defined the --primary-color-darker variable, or it is not available for this scope, var() will return darkred.

Inheritance

Another feature of custom properties is that they do inherit. This means if a child has no set value for a custom variable, it will inherit the value for it from it's parent.

This means that:

<div class="main">
    <div class="content-1"></div>
    <div class="content-2"></div>
</div>
<div class="modal"></div>

having css:

.main {
    --custom-color: blue;
}
.content-1 {
    --custom-color: lightblue;
}

When we use var(--custom-color) for each element, will return the following values:

  • for element with class main - blue;
  • for element with class content-1 - lightblue;
  • for element with class content-2 - blue, inherited from parent;
  • for element with class modal - invalid value.

Don't hesitate to contact me to report any mistakes or just to say hi.

#shorts #css

Prev

...

Copyright © 2021, Atanas Stanilov

Made with lots of and ❤️

Contact me