DEV Community

Cover image for CSS custom properties - Cheatsheet
Vincent Humeau
Vincent Humeau

Posted on • Updated on • Originally published at vinceumo.github.io

CSS custom properties - Cheatsheet

This note was originally posted on my DevNotes


CSS custom properties, also known as CSS variables. represent custom properties that can be declared and be called in your CSS.

Declare a custom property in CSS

To declare a custom property in your CSS, you need to use the -- syntax:

:root {
  --colorPrimary: hsla(360, 100%, 74%, 0.6);
}

Notice the :root pseudo-class selector, we can declare our variables globally using it. We can as well declare them using other selectors, they will be then be scoped in these ones.

.theme-dark {
  --colorPrimary: hsla(360, 100%, 24%, 0.6);
}

Use a custom property in CSS

To use a CSS custom property in your CSS you can use the var() function

:root {
  --colorPrimary: tomato;
}

.theme-dark {
  --colorPrimary: lime;
}

body {
  background-color: var(--colorPrimary);
}

In this case, body will have a background colour of tomato. But body.theme-dark of lime.

Use custom properties without units

CSS custom properties can be declared without units if they are used with the calc() function.

:root {
  --spacing: 2;
}

.container {
  padding: var(--spacing) px; /*Doesn't Work 😫*/
  padding: calc(var(--spacing) * 1rem); /*Will output 2rem 😃*/
}

Use custom properties with JavaScript

To get a custom property we can use the following:

getComputedStyle(element).getPropertyValue("--my-var");

// Or if inline
element.style.getPropertyValue("--my-var");

To update the custom property value:

element.style.setProperty("--my-var", newVal);

Example of getting and replacing values:

In the following example, we use the dat.gui controller library to change the value of --scenePerspective, --cubeRotateY, --cubeRotateX custom properties. This method makes it easier to apply a new style, as do not have to apply inline style on each Dom elements.

Resources


Top comments (0)