DEV Community

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

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

29 8

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


Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more