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


Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay