How to use CSS Variables

CSS variables, also known as custom properties, are a powerful feature that allows you to store and reuse values throughout your stylesheets. This can lead to cleaner, more maintainable, and more dynamic CSS.

They offer several advantages, including:

Reduced repetition

CSS variables allow you to define a value once and reuse it multiple times throughout your stylesheet. For example, you can set a variable for a color or a font size and then use that variable wherever needed, reducing the need for repetitive declarations.

Theming

With CSS variables, you can create themes for your website by defining variables for colors, fonts, spacing, etc. Changing these variables can dynamically alter the entire appearance of your site. For instance, adjusting a few variable values can switch between light and dark themes or completely transform the color scheme.

Dynamic styling

CSS variables enable dynamic styling by allowing you to modify their values using JavaScript. This means you can respond to user interactions or other conditions by updating variable values on the fly. For instance, you could change a color variable when a button is clicked or adjust spacing based on screen size changes.

Here's a detailed explanation with examples:

Declaring CSS Variables

To declare a CSS variable, you use the -- prefix followed by a name and assign it a value using the var() function.

:root { --primary-color: #007bff; --secondary-color: #6c757d; }

In this example, --primary-color and --secondary-color are CSS variables defined globally within the :root pseudo-class.

Using CSS Variables

Once defined, you can use CSS variables anywhere in your stylesheet by referencing them with the var() function.

button { background-color: var(--primary-color); color: white; border: 2px solid var(--secondary-color); padding: 10px 20px; }

In this example, the background-color and border-color properties of the button are set to the values of --primary-color and --secondary-color respectively.

Dynamic Changes

One of the key benefits of CSS variables is that they can be dynamically changed using JavaScript, allowing for dynamic theming or adjustments based on user interactions.

document.documentElement.style.setProperty('--primary-color', '#ff0000');

This JavaScript code changes the value of --primary-color to red. Any element that uses this variable for styling will now reflect this change.

Cascading and Inheritance

CSS variables follow the same cascading and inheritance rules as other CSS properties, allowing you to override them in specific contexts.

.container { --primary-color: #ff0000; } button { background-color: var(--primary-color); /* Will be red */ }

In this example, the --primary-color variable is overridden within the .container class, affecting all elements inside it that use this variable.

Fallback Values

You can provide fallback values for CSS variables using the second parameter of the var() function.

button { background-color: var(--primary-color, #007bff); /* Fallback to default blue if --primary-color is not defined */ }

In this example, if --primary-color is not defined, the button's background color will default to #007bff.

Media Queries

CSS variables can also be used within media queries to create responsive designs.

@media (max-width: 600px) { button { padding: 5px 10px; } }

Using the @property rule

@property --secondary-color, '--secondary-color', { initial-value: green; inherits: true; } .heading { color: var(--secondary-color); }

Here, --secondary-color is declared with an initial value of green and set to inherit its value from parent elements.

Scope and Inheritance | CSS Variables

  1. Global scope: CSS variables declared within the :root selector are accessible anywhere in the document. They can be used across multiple selectors, making them handy for maintaining consistent styles across the entire webpage without repeating values.
  2. Local scope: Variables declared within a specific selector have a local scope, accessible only within that selector and its child elements. This encapsulation helps in organizing styles and prevents unintentional interference with other parts of the document.
  3. Inheritance: CSS variables with the inherits property set to true inherit their values from their parent elements. This allows for cascading of variable values down the DOM tree, making it convenient to propagate style changes across nested elements while maintaining consistency and reducing redundancy.

Best Practices

  1. Use descriptive variable names for better readability and maintainability.
  2. Define global variables consistently, typically at the beginning of your stylesheet.
  3. Consider using a linter or preprocessor to enforce variable naming conventions and catch errors.
Examples:

A complete HTML and CSS example that demonstrates the comprehensive use of CSS variables:

This example demonstrates the following:

  1. CSS variables are defined using the :root pseudo-class.
  2. The defined variables (--primary-color, --secondary-color, and --border-radius) are used throughout the stylesheet to set colors, border radius, etc.
  3. The JavaScript part changes the primary and secondary colors when the button is clicked, demonstrating dynamic styling.
Full Source:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Variables Example</title> <style> /* Define CSS variables */ :root { --primary-color: #3498db; --secondary-color: #2ecc71; --border-radius: 5px; } /* Use CSS variables */ body { font-family: Arial, sans-serif; background-color: #f2f2f2; color: var(--primary-color); } h1 { color: var(--secondary-color); } .button { background-color: var(--primary-color); color: white; padding: 10px 20px; border: none; border-radius: var(--border-radius); cursor: pointer; } .button:hover { background-color: var(--secondary-color); } .container { margin: 20px; padding: 20px; border: 2px solid var(--primary-color); border-radius: var(--border-radius); } </style> </head> <body> <h1>CSS Variables Example</h1> <div class="container"> <p>This is a paragraph with some text.</p> <button class="button">Click me</button> </div> <script> // JavaScript to demonstrate dynamic styling const button = document.querySelector('.button'); button.addEventListener('click', function() { document.documentElement.style.setProperty('--primary-color', '#e74c3c'); document.documentElement.style.setProperty('--secondary-color', '#c0392b'); }); </script> </body> </html>

Theming with CSS Variables

Imagine you have a website with a light and dark theme. You can use CSS variables to define shared colors, fonts, and other styles while allowing easy switching between themes:

Full Source:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Themed Website</title> <style> :root { --theme: light; /* Default theme */ /* Light theme variables */ --theme-light-primary: #333; --theme-light-secondary: #ccc; --theme-light-font: sans-serif; /* Dark theme variables */ --theme-dark-primary: #fff; --theme-dark-secondary: #ddd; --theme-dark-font: serif; } body { background-color: var(--primary-color); color: var(--secondary-color); font-family: var(--font-family); transition: background-color 0.5s, color 0.5s, font-family 0.5s; } /* Theme toggle button */ .theme-toggle { position: fixed; top: 20px; right: 20px; z-index: 999; } /* Hide the checkbox */ .theme-toggle input { display: none; } /* Style the label as a toggle button */ .theme-toggle label { display: inline-block; width: 60px; height: 30px; background-color: #ccc; border-radius: 15px; cursor: pointer; transition: background-color 0.3s; } /* Style the indicator */ .theme-toggle label:after { content: ''; display: block; width: 30px; height: 30px; border-radius: 50%; background-color: white; transform: translateX(0); transition: transform 0.3s; } /* Adjust styles when checked */ .theme-toggle input:checked + label { background-color: #4CAF50; } .theme-toggle input:checked + label:after { transform: translateX(30px); } </style> </head> <body> <input type="checkbox" id="theme-toggle" class="theme-toggle"> <label for="theme-toggle"></label> <h1>Themed Website</h1> <p>This is an example of a themed website. Click the button to toggle between light and dark themes.</p> <script> const themeToggle = document.getElementById('theme-toggle'); themeToggle.addEventListener('change', function() { if (this.checked) { document.documentElement.style.setProperty('--primary-color', 'var(--theme-dark-primary)'); document.documentElement.style.setProperty('--secondary-color', 'var(--theme-dark-secondary)'); document.documentElement.style.setProperty('--font-family', 'var(--theme-dark-font)'); } else { document.documentElement.style.setProperty('--primary-color', 'var(--theme-light-primary)'); document.documentElement.style.setProperty('--secondary-color', 'var(--theme-light-secondary)'); document.documentElement.style.setProperty('--font-family', 'var(--theme-light-font)'); } }); </script> </body> </html>

This example includes a theme toggle button that, when clicked, switches between light and dark themes. The CSS variables are updated dynamically to reflect the chosen theme.

Conclusion

CSS variables allow you to define reusable values that can be used throughout your stylesheet. They provide benefits such as reduced repetition by defining values once, theming by easily changing the overall look and feel of a website, and dynamic styling through JavaScript manipulation.