CSS variables are a modern CSS specification that are the basis of any web application, as they are the basic building block of data-driven applications. Through variables, we can reduce coding and maintenance time, allowing web developers to develop compatible software applications between different browsers. Using variables, coders reduce repetitive tasks and store values that can be used throughout the lifetime of the application or the browser instance. In the past, this was only possible with SaSS (simply awesome style sheets) or LESS preprocessors.
What Are CSS Variables?
CSS variables are custom properties in which web developers can store values, which, in turn, can be used anywhere on your website. Unlike programming languages that support a simple initialization and substitution syntax, CSS variables must be specifically defined if they are initialized or replaced, using different syntaxes. The initialization of a variable is done by prefixing “–” to the variable name. For example, the following syntax initializes the variable main-color to gray:
--main-color: gray
It can be used anywhere inside the code with the given value. If we want to replace the property of the variable, we use the CSS property called var():
color: var(- main-color)
Read: Using Angular to Read Sass Variables
CSS var() Function
The var() function is used to add value to a CSS variable. CSS variables can be created globally or locally and are very useful when you use them as part of web application design. Instead of always changing colors, you can place color values in variables and call them when needed, considerably optimizing your content.
The CSS var() function syntax is as follows:
var(--name, value)
Here is a more concrete example of how to use the var() function in CSS and HTML:
<!DOCTYPE html> <html> <head> <style> .content, div { padding: 8px; display: auto; border: none; border-radius: 15px; } div { margin: 12px; } :root { --yellow: #ffc300; --purple: #c83349; --blue: #36486b; --white: #ffffff; --light-grey: #d3d3d3; --border-yellow: 1px solid var(--yellow); --border-purple: 1px solid var(--purple); --border-blue: 1px solid var(--blue); } .content { background-color: var(--light-grey); } .box-1 { border: var(--border-yellow); color: var(--yellow); background-color: var(--white); border-radius: 15px; } .box-2 { border: var(--border-purple); color: var(--purple); background-color: var(--white); border-radius: 15px; } .box-3 { border: var(--border-blue); color: var(--blue); background-color: var(--white); border-radius: 15px; } .box-1 button { background-color: var(--yellow); color: var(--white); } .box-2 button { background-color: var(--purple); color: var(--white); } .box-3 button { background-color: var(--blue); color: var(--white); } button { border-radius: 15px; border: none; } </style> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Var() function</title> </head> <body> <div class="content"> <div class="box-1"> <p class="first">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras ut feugiat urna. Sed sit amet elementum tortor. Mauris sed nisi congue purus dignissim lobortis.</p> <button type="button">Click here!</button> </div> <div class="box-2"> <p class="second">Nulla molestie posuere nisl, nec sodales felis lacinia eu. Praesent erat massa, scelerisque quis ex sit amet, rutrum varius enim.</p> <button type="button">Click here!</button> </div> <div class="box-3"> <p class="third">Curabitur pretium tortor sollicitudin lectus vulputate interdum eget vitae quam. Morbi tincidunt eleifend porttitor.</p> <button type="button">Click here!</button> </div> </div> </body> </html>
Read: Testing for Variable Emptiness with JavaScript
What is Scope in CSS Variables?
There are two types of scope a variable can have in CSS. They are:
-
- Global scope: To create a global scope variable, you must declare it in the :root selector or the selector matching the root element of the document. Once the variable is declared, it can be accessed from the beginning to the end of the document.
- Local scope: to create a local scope variable, you must declare it inside the selector that will use it.
A brief note about CSS variable inheritance – the value of an item is inherited from the parent, or if no value is set for a custom property of a particular item.
Read: A Guide to CSS Variable Scoping
How to Change Variable Values with JavaScript
One of the most interesting points for web developers who use JavaScript is that CSS variables can be manipulated and managed through this scripting language. To use variables in CSS via JavaScript, their value is obtained similar to how JavaScript handles other properties. Let’s look at an example showing how to change CSS variables with JavaScript:
<!DOCTYPE html> <html> <head> <style> .content, div { padding: 8px; display: auto; border: none; border-radius: 15px; } div { margin: 12px; } :root { --yellow: #ffc300; --purple: #c83349; --blue: #36486b; --white: #ffffff; --light-grey: #d3d3d3; --border-yellow: 1px solid var(--yellow); --border-purple: 1px solid var(--purple); --border-blue: 1px solid var(--blue); } .content { background-color: var(--light-grey); } .box-1 { border: var(--border-yellow); color: var(--yellow); background-color: var(--white); border-radius: 15px; } .box-2 { border: var(--border-purple); color: var(--purple); background-color: var(--white); border-radius: 15px; } .box-3 { border: var(--border-blue); color: var(--blue); background-color: var(--white); border-radius: 15px; } .box-1 button { background-color: var(--yellow); color: var(--white); } .box-2 button { background-color: var(--purple); color: var(--white); } .box-3 button { background-color: var(--blue); color: var(--white); } button { border-radius: 15px; border: none; font-color: white; } </style> <script> var rt = document.querySelector(":root"); function change_color() { rt.style.setProperty("--light-grey", "lightblue"); } </script> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Var() function</title> </head> <body> <h3>Change CSS variable through JavaScript</h3> <div class="content"> <div class="box-1"> <p class="first">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras ut feugiat urna. Sed sit amet elementum tortor. Mauris sed nisi congue purus dignissim lobortis.</p> <button type="button">Click here!</button> </div> <div class="box-2"> <p class="second">Nulla molestie posuere nisl, nec sodales felis lacinia eu. Praesent erat massa, scelerisque quis ex sit amet, rutrum varius enim.</p> <button type="button">Click here!</button> </div> <div class="box-3"> <p class="third">Curabitur pretium tortor sollicitudin lectus vulputate interdum eget vitae quam. Morbi tincidunt eleifend porttitor.</p> <button type="button">Click here!</button> </div> <button type="button" onclick=" change_color()">Change variables with JavaScript</button> </div> </body> </html>
In the example above, we stored the selector: root in a variable, then created a function named change_color() and, through it, changed the existing background color to a new one.
Read: Math Functions in CSS
How to Use CSS Variables in Media Queries
Now we will show you how to change the value of a CSS variable in a media query. Media query refers to setting style rules for different devices, such as tablets, mobile phones, and different screen sizes:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Variabiles CSS in media query</title> <style> :root { --light-grey: #d3d3d3; --white: #ffffff; } .box { --fontsize: 15px; } body { background-color: var(--light-grey); } .box { color: var(--light-grey); background-color: var(--white); padding: 25px; font-size: var(--fontsize); } @media screen and (min-width: 481px) { .box { --fontsize: 35px; } } </style> </head> <body> <h3 style="color: white;">Using variables CSS in media queries</h3> <div class="box"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus commodo, lorem vitae mollis tincidunt, turpis sapien vehicula metus, sit amet hendrerit dui neque sit amet velit. Mauris id purus quis nibh convallis bibendum. Sed in ex ac dolor ornare consequat ac at leo. Duis tempor leo eleifend aliquet dignissim. Sed imperdiet lectus ut ultricies pretium. </p> </div> </body> </html>
In the example above, if the browser width is less than 481px, the font size becomes 15px. When the size is larger than 481px, then the font size changes to 35px.
Final Thoughts on CSS Variables
CSS variables are very useful for managing and organizing large or small amounts of CSS, reducing code duplication, eliminating the use of preprocessors, having the ability to be able to be declared anywhere, and preventing mistakes. They offer the ability to define the same property at different levels of specificity, making it much easier for web developers to work, and making code easier to read and understand.