DEV Community

Cover image for Introduction to Variables in CSS🔥
Ahmed Murtaza
Ahmed Murtaza

Posted on

Introduction to Variables in CSS🔥

Complex websites have very large amount of CSS, often with a lot of repeated values. For instance, we have same color value used in multiple files, searching it globally and replacing would be a big cost, instead we can use CSS variables to store repeated values at one place and reference them where ever it's required.

What is :root ?

:root is a CSS pseudo-class which is considered equivalent to <html> in HTML, referring to the entire document. We declare variables inside :root and can use everywhere. Variables are referred by double hyphens signature --main-color: hotpink

:root {
  --main-color: hotpink;
}
Enter fullscreen mode Exit fullscreen mode

Referencing a variable

Once a variable is set in :root, we can easily access it with in any selector using var function as below:

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

.some-other-class {
   background-color: var(--main-color);
}
Enter fullscreen mode Exit fullscreen mode

Declaring a variable inside :root simply means we can access the variable within any CSS selector, as :root is considered to be the top most parent for all selectors, just as <html> for all other tags in HTML. Similarly, we can define the variable inside any other selectors too:

HTML

<!-- first  element -->
<div class="first-parent">
    <div class="first-parent__child">First child text</div>
</div>
<!-- /first  element -->

<!-- second  element -->
<div class="second-parent">
    <div class="second-parent__child">Second child text</div>
</div>
<!-- /second  element -->
Enter fullscreen mode Exit fullscreen mode

CSS

.first-parent {
  --main-color: orange;
}
.first-parent__child {
  background-color: var(--main-color);
}
.second-parent__child {
  background-color: var(--main-color);  /* this won't work */
}
Enter fullscreen mode Exit fullscreen mode

What above shows is that --main-color can be referenced only within selectors which refers to either first-parent itself or it's children tags, and not outside first-parent tag.

That's it for today 🎉. Would love to hear your thoughts, and do share me how often you embrace the power of CSS variables in your projects. Stay tuned 👋

Top comments (0)