How To Use CSS Variables – Very Simple Examples

Welcome to a quick tutorial on how to use CSS variables. Just heard of CSS variables, or want to create some dynamic styles with them?

CSS variables can be used in 2 simple steps:

  1. Define the CSS variable and assign a value – :root { --myVar: red; }
  2. Attach the variable to a property – .myClass { color: var(--myVar); }

Yes, it’s that easy. But read on for more examples!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes CSS Variables Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

CSS VARIABLE EXAMPLES

All right, let us now get into the examples of using CSS variables.

 

1) BASIC CSS VARIABLE

1-basic-var.html
<!-- (A) CSS -->
<style>
/* (A1) DEFINE CSS VAR */
:root { --myColor: red; }
 
/* (A2) ASSIGN CSS VAR TO PROPERTY */
.foo { color: var(--myColor); }
.bar { background-color: var(--myColor); }
</style>

<!-- (B) HTML -->
<p class="foo">Red Font</p>
<p class="bar">Red Background</p>

Red Font

Red Background

For you absolute beginners, you can think of variables as “containers for values”. In simple terms:

  • We declared a variable called --myColor in this example, and assigned the value of red to it.
  • Then, we attach the variable to properties – color: var(--myColor) and background-color: var(--myColor).

What’s the point of CSS variables? If we want to change the color from red to blue in the future, we can easily set --myColor: blue.

 

 

2) CSS VARIABLE SCOPE

2-scope.html
<!-- (A) CSS -->
<style>
/* (A1) --BIGSIZE WILL ONLY APPLY TO .HELLO CLASS */
.hello { --bigSize: 2em; }
 
/* (A2) ASSIGN CSS VAR TO PROPERTY */
.hello { font-size: var(--bigSize); }
.world { font-size: var(--bigSize); }
</style>
 
<!-- (B) HTML -->
<p class="hello">Big Size Font</p>
<p class="world">Big Size Not Apply</p>

Big Size Font

Big Size Not Apply

  • Notice that we defined :root { --myColor: red; } in the previous example? Yes, :root pretty much refers to the DOM root, effectively making the --myColor variable available in all elements.
  • What if we want to limit where a CSS variable is applicable? Simply specify and limit its scope. In this example, .hello { --bigSize: 2em; } will restrict the --bigSize variable to apply within the .hello CSS class only.

 

3) STYLE FALLBACK

3-fallback.html
<!-- (A) CSS -->
<style>
/* USE BLUE IF --MYCOLOR CANNOT BE RESOLVED */
.fooz { color: var(--myColor, blue); }
</style>

<!-- (B) HTML -->
<p class="fooz">Blue Text</p>

Blue Text

This example shouldn’t be too much of a mystery, we can define a fallback value if the variable cannot be resolved… Don’t be surprised, it is easy to forget to define variables in a massive project, or even assign an invalid value.

 

 

4) INHERITANCE & OVERRIDING

4-inherit-override.html
<!-- (A) CSS -->
<style>
/* (A1) PARENT */
.theParent { --maincolor: red; }
.theParent { color: var(--maincolor); }
 
/* (A2) CHILD - OVERRIDE */
.childThree { --maincolor: green; }
.childThree { color: var(--maincolor); }
</style>

<!-- (B) HTML -->
<div class="theParent">
  <div class="childOne">Red Text</div>
  <div class="childTwo">Red Text</div>
  <div class="childThree">Green Text</div>
</div>
Red Text
Red Text
Green Text

Yes, the rule of inheritance also applies to CSS variables. In this example:

  • The parent container .theParent is set to color: var(--maincolor), which resolves to color: red.
  • The children <div class="childOne"> and <div class="childTwo"> will inherit this color, resolves to color: red.
  • But we override .childThree with --maincolor: green.

 

5) GET & SET CSS VARIABLE WITH JAVASCRIPT

5-js-html
<!-- (A) CSS -->
<style>
#demo {
  --myColorX : red;
  color: var(--myColorX);
}
</style>
 
<!-- (B) HTML -->
<p id="demo">This is some dummy text.</p>
 
<!-- (C) JAVASCRIPT -->
<script>
function getSetVar () {
  // (C1) GET HTML ELEMENT
  var target = document.getElementById("demo");

  // (C2) GET CSS VARIABLE
  var current = getComputedStyle(target).getPropertyValue("--myColorX");
  console.log(current);

  // (C3) SET CSS VARIABLE
  target.style.setProperty('--myColorX', 'pink');
}
</script>
<input type="button" value="Get Set CSS Var" onclick="getSetVar()"/>

This is some dummy text.

For this final example – Yes, we can also use Javascript to manipulate the CSS variables as well.

  • To get the value of a CSS variable – getComputedStyle(TARGET).getPropertyValue(VARIABLE)
  • To change the value of a CSS variable – TARGET.style.setProperty(VARIABLE, NEW VALUE)

 

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

INFOGRAPHIC CHEAT SHEET

How To Use CSS Variable (Click To Enlarge)

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *