CSS - Variable (Custom Property)

About

CSS variables 1) are variable that can be used in a css property value.

They are also known as:

Example

Set

They are set using the custom property notation (e.g. with the prefix in the property name)

For example, if you want to set dominant color of your color scheme:

  • for you whole page (on the root)
:root {
  --primary-color: black;
}
  • for particulars element with a selector. example for all element with the class note
.note {
  --primary-color: skyblue;
}

Usage

The css variable can be set on the property value by using the var() 2) function.

.note {
   background-color: var(--primary-color);
   padding: 2rem;
}

Example:

  • with the below html
<div class="note">
A skyblue note
</div>
  • and the variable set to skyblue the output is:

Calculation

You can also use them with all css function to get more complex logical styling.

Example:

:root, * {
    --space-xxxxs: calc(0.125 * var(--space-unit));
    --space-xxxs: calc(0.25 * var(--space-unit));
    --space-xxs: calc(0.375 * var(--space-unit));
    --space-xs: calc(0.5 * var(--space-unit));
    --space-sm: calc(0.75 * var(--space-unit));
    --space-md: calc(1.25 * var(--space-unit));
    --space-lg: calc(2 * var(--space-unit));
    --space-xl: calc(3.25 * var(--space-unit));
    --space-xxl: calc(5.25 * var(--space-unit));
    --space-xxxl: calc(8.5 * var(--space-unit));
    --space-xxxxl: calc(13.75 * var(--space-unit));
    --component-padding: var(--space-md);
}

Powered by ComboStrap