Home > AI > Language > CSS >

variables

Complex websites have very large amounts of CSS, often with a lot of repeated values. For example, the same color might be used in hundreds of different places, requiring global search and replace if that color needs to change. Custom properties allow a value to be stored in one place, then referenced in multiple other places. An additional benefit is semantic identifiers. For example, --main-text-color is easier to understand than #00ff00, especially if this same color is also used in other contexts.

# define
element {
  --main-bg-color: brown;
}
# access
element {
  background-color: var(--main-bg-color);
}

A common best practice is to define custom properties on the :root pseudo-class, so that it can be applied globally across your HTML document:

:root {
  --main-bg-color: brown;
}

Note: Custom property names are case sensitive — --my-color will be treated as a separate custom property to --My-color.

Inheritance

<div class="one">
  <div class="two">
    <div class="three"></div>
    <div class="four"></div>
  </div>
</div>
<style>
.two {
  --test: 10px;
}

.three {
  --test: 2em;
}
</style>

In this case, the results of var(--test) are:

  • For the class="two" element: 10px
  • For the class="three" element: 2em
  • For the class="four" element: 10px (inherited from its parent)
  • For the class="one" element: invalid value, which is the default value of any custom property

Leave a Reply