Learn CSS Custom properties ( CSS variables) in 2 minutes🙌

Learn CSS Custom properties ( CSS variables) in 2 minutes🙌

·

2 min read

Hi there, Know that I'm filled with joy having you today! Your presence brings warmth to my heart💓

What are CSS Custom properties?

CSS Custom properties are characteristic that allows you to change many elements of your design that are not included in the Design tab. They can be set using custom property notation (e.g., --main-color: black;) and can be accessed using the var() function (e.g., color: var(--main-color);).

The benefit of CSS Custom properties

Most complex websites have very large amounts of CSS, with a lot of repeated values. For example, the same color might be used in hundreds of different places, requiring global search and replacement if that color needs to change. Custom properties allow a value to be stored in one place, then referenced in multiple other places.

:root {
    /* colors */
    --color-dark: #000000;
    --color-light: #00ff00;
}

div{
    background-color: var(--color-dark);
    color: var(--color-white);
}
nav{
    background-color: var(--color-white);
    color: var(--color-black);
}

semantic identifiers

For example, --color-white is easier to understand than #00ff00

CSS Custom properties usage

Declaring CSS Custom properties is done using a custom property name that begins with a double hyphen (--), and a property value that can be any valid CSS value. Like any other property, this is written inside a ruleset, like so:

element {
  --color-dark: #000000;
}

Note that the selector given to the ruleset defines the scope that the custom property that can be used. 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 {
 --color-dark: #000000;
}

However, this doesn't always have to be the case: you maybe have a good reason for limiting the scope of your custom properties.

Note:

Custom property names are case-sensitive

--color-dark will be treated as a separate custom property to --Color-dark

As mentioned earlier, you use the custom property value by specifying your custom property name inside the var() function, in place of a regular property value:

element {
  background-color: var(--color-dark);
}

Hope you enjoyed your reading, Stay tuned! Peace out ✌😎

Â