Skip to main content

Command Palette

Search for a command to run...

CSS Variables Tutorial

Learn How to Work with Custom Properties aka 'Variables'

Published
3 min read
CSS Variables Tutorial
R

Passionate Software Engineer with three years of experience, dedicated to creating robust and scalable web applications. I have a strong foundation in JavaScript, React, Python, and Node.js, and enjoy working with modern tech stacks to build innovative solutions. I'm committed to writing clean and efficient code, following best practices, and staying updated with the latest industry trends.

Throughout my career, I've gained valuable experience in full-stack development, including frontend design, backend development, and database management. I love solving complex problems and implementing creative solutions that enhance user experiences. I believe in the power of collaboration and thrive in cross-functional teams where I can contribute my skills and learn from others.

Beyond coding, I am an avid learner and enjoy sharing my knowledge with the developer community. I regularly contribute to open-source projects, write technical blog posts, and engage in discussions on emerging technologies. I'm always seeking opportunities to expand my skill set and stay at the forefront of software engineering.

Custom Properties (commonly known as CSS Variables) are a modern addition to CSS. If you’ve worked with programming languages such as JavaScript, Python, etc, you’ll know that variables are extremely useful.

A variable is a name that refers to a value, and by using variables in CSS we greatly reduce code repetition & create much more easily maintainable stylesheets.

Defining a CSS Variable

We define a variable by using a name beginning with a double hyphen (--variable-name), followed by a colon and a value (any valid CSS value):

:root {
  --main-color: green;
}

The :root pseudo-class is a special selector, that applies the style globally to the HTML document. More on this later!

The variable can be accessed using var():

p {
  color: var(--main-color)
}

Defining Variables in Elements

We can define CSS Variables inside of any element:

:root {
  --default-padding: 30px 30px 20px 20px;
}
body {
  --main-bg-color: black;
}
p {
  --main-color: light blue;
}
a:hover {
  --main-color: red;
}

Variable Scope

Each variable is available only to child elements of the selector they are defined in — this is the ‘scope’.

Let’s see this in the context of our previous example using :root:

:root {
  --main-color: green;
}

:root is a special pseudo-class that refers to the root element of a tree.

In an HTML document, the :root selector refers to the HTML element. And in fact, it has a higher specificity than HTML so it will always take priority.

So when a variable is applied to :root it’s considered to have ‘global scope’ & is available to all elements.

If we added a variable to a main element, it’d only be available to children of main:

main {
  --main-color: light blue;
}

If we attempt to use it using it outside of this element, it won’t work.

So our two variables are as follows:

:root {
  --main-color: green;
}
main {
  --main-color: light blue;
}

Our --main-color will be green anywhere in our document, except for main and any of its child elements — they will be lightblue.

Bonus tips...

Case sensitivity

CSS variables are case-sensitive!

:root {
 --color: green;
 --COLOR: light blue;
}

So --color and -COLOR are two separate variables.

Using variables in HTML

Variables can be used directly in HTML, like so:

<!--HTML-->
<html style="--size: 800px">
body {
  max-width: var(--size)
}

Using variables within variables

A variable can be used within another variable:

--base-red-color: #f00;
--background-gradient: linear-gradient(to top, var(--base-red-color), #222);

Using variables with math

CSS variables can be used with the calc() function:

--input-width: 500px;
max-width: calc(var(--input-width) / 2);

Using variables with media queries

We can make CSS variables conditional with media queries!

The following code changes the value of the padding, based on the screen size:

:root {
    --padding: 25px 
}
@media screen and (max-width: 750px) {
    --padding: 10px
}

Setting a fallback value for var()

When you use the var() function you can define a second parameter. This value will be used if the custom property is not found:

width: var(--custom-width, 33%);

Conclusion

I’m sure you can tell that the use of CSS variables will make your code much more readable and maintainable.

They also significantly improve the ease of change across larger codebases. If you set all your constants in a separate CSS file, you won’t find yourself jumping through thousands of lines of code, whenever you want to make a simple change!

If you liked this blog post, follow me on Twitter where I post daily about Tech related things!

🌎 Let's Connect

CSS Tutorials

Part 19 of 25

Learn the ins and outs of CSS with my comprehensive blog series! From the basics of CSS syntax to advanced techniques like responsive design and CSS animations, these tutorials will help you!

Up next

CSS Media Queries Tutorial

How to Build Responsive Web Pages with Media Queries

More from this blog

Rembert Designs Blog | Helping Web Developers And Designers with Resources

107 posts

Passionate Software Engineer with three years of experience, dedicated to creating robust and scalable web applications. I have a strong foundation in JavaScript, React, Python, and Node.js.