DEV Community

Cover image for CSS variables: What are they and how to use them
John Palmgren
John Palmgren

Posted on

3 1

CSS variables: What are they and how to use them

What are they

CSS custom properties aka CSS variables allow you to define a property in a variable that you can use over and over again. There are a number of use cases for this: often you will use the same colors for a brand or a particular theme. The big benefit of using variables for commonly used properties is that if you need to change it further down the line you can simply change the variable. This will save you from having to find everywhere in your code that you used that property.

How to use them

Apply the variable to an element

You first need to declare what element it should be applied to. You can apply it to any element but it is common to apply it to the root element so it can be used anywhere in your CSS (global scope). Use the :element {} syntax to select the element. You can choose any name for your variables but they are case sensitive.

:root {
  --bg-color: #4B6CDB;
  --text-color: #fff;
}
Enter fullscreen mode Exit fullscreen mode

Calling the variable

You can call the variable by using var(). Instead of putting in the property name call the variable name inside the var function

.myClass {
  background-color: var(--bg-color)
  color: var(--text-color)
}
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (2)

Collapse
 
prakhart111 profile image
Prakhar Tandon

Hey John,
Want to add a few points on CSS variables.

  • It is recommended to add a fallback condition in case of inability to access the variable, CSS will use that fallback item.
.myClass {
  background-color: var(--bg-color , black)
  color: var(--text-color , white)
}
Enter fullscreen mode Exit fullscreen mode

The values after the comma, represent fallback values.

  • CSS variables are inherited and are also available in any of that selector's decedent.

A variable declared in :root , means it's in the root element ( think it as html tag )
Hence it is accessible globally.

And yes, on dev, to get such colourful code, just use "js" after first commas

Cheers !

Collapse
 
johnpalmgren profile image
John Palmgren

Thanks for your comment. Some great points ❤

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