Create your account

Already have an account? Login here

Note: By joining, you will receive periodic emails from Coursetro. You can unsubscribe from these emails.

Create account

CSS Variables without Sass? CSS Variables Tutorial

By Gary simon - Feb 27, 2018

If you've ever worked on a fairly large project, you probably found yourself reusing the same values over and over again. This, of course, is problematic when you need to make a change. You're left there using your code editor's find and replace feature and even then, you might screw something up unintentionally.

So, you leveled up and used a CSS preprocessor like Sass, which gave you CSS variables!  Yay, but still, the necessity of adding a second layer on top of CSS is less preferable than if CSS were to support variables natively.

Well, CSS variables are now here. Not only are they here, but they allow you to do a few things that you couldn't even do with preprocessors!

In this CSS variables tutorial, I'm going to show you how to start using these variables in your own projects.

Let's get started.

We have some pretty awesome courses

Check them out

If you prefer watching a video..

Be sure to Subscribe to the Official Coursetro Youtube Channel for more videos.

Starting a New Project

We're going to keep things simple. Create a new folder and place within it 2 files:

  • index.html
  • main.css

For the index.html, paste the following contents:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>CSS Variables Tutorial</title>
    <link rel="stylesheet" href="main.css">
</head>
<body>
    <div class="wrapper">
        <div class="container">
            <h1>My Awesome CSS Variables</h1>
            <p>It has only taken them over 2 decades to integrate...</p>

            <button>I'm a button</button>
        </div>
        <p>I'm another paragraph down here.</p>
    </div>
</body>
</html>

Here, we're just referencing the main.css file that we will work in, and some very basic HTML.

Defining CSS Variables

In the main.css file, here is how you can define a basic CSS variable (tehcnically it's a property, but we'll call them variables):

:root {
    --site-bg: #f1e9c5;
}

First, you will notice the :root psuedo-class. Defining a variable in here will provide all elements within the HTML access to this variable.

A variable is declared by prefixing two dashes --, and then you give it a custom name. Finally, you give the variable a value.

In our case, the variable name is --site-bg and the value is #f1e9c5.

Using CSS Variables

We've defined our very first CSS variable, so, how do we use it?  Simple:

:root {
    --site-bg: #f1e9c5;
}

body {
    background: var(--site-bg);
}

If you view the index.html document in the browser, you will see that the background is a light yellow.

You use a variable by wrapping the variable name within the var() function.

CSS Variable Inheritance

You can define CSS variables on other selectors (not just :root), and these variables inherit.  To demonstrate this, let's say for instance that we want only the type within our .container element to be bold.

We would set it up like this:

.container {
    --type-weight: bold;
}

.wrapper, .container {
    font-weight: var(--type-weight);
}

Notice that we've also added the .wrapper class, which has a paragraph element within it. Being that the --type-weight variable is defined on the .container class, the type elements outside of it will not be bold.

The result in the browser looks like this:

CSS Variable Fallback Values

The variable() function allows you to specify multiple levels of fallbacks. For instance, in the case above, we could make bold a fallback value in the event that our --type-weight variable is not defined:

.wrapper, .container {
    font-weight: var(--type-weight, bold);
}

If you save and refresh, you will see that both paragraphs are now bold.

CSS Variables & JavaScript

You can access and set CSS variable values from JavaScript!

To retrieve a value, visit index.html and add the following just before the closing </body> tag:

    <script>

        var body = document.querySelector('body')
        
        myVar = getComputedStyle(body).getPropertyValue("--site-bg");
        console.log(myVar);
    
    </script>

If you refresh and view the console (ctrl-shift-i), you will see the color code value!

You can even set a CSS variable with JavaScript:

    <script>
        var body = document.querySelector('body')
        
        body.style.setProperty("--site-bg", "#ffcc00");

        myVar = getComputedStyle(body).getPropertyValue("--site-bg");
        console.log(myVar);
    </script>

Here, we're first setting the property (variable) with .setProperty and then we're retrieving the value. As you will see with the new background and console.log, the variable has been overwritten with our JavaScript!

Conclusion

With the addition of the new CSS Grid and now CSS variables, CSS is most certainly becoming much more enjoyable to work with!


Share this post




Say something about this awesome post!