CSS CSS Tutorial CSS Advanced CSS Responsive Web Design(RWD) CSS Grid CSS Properties Sass Tutorial Sass Functions



CSS Variables

CSS Variables, also known as CSS Custom Properties, are a powerful feature introduced in CSS3 that allow developers to define reusable values in CSS. These values can be used throughout the stylesheet, making it easier to maintain and update the design of a website or application.

Before CSS Variables, developers had to use preprocessor languages like Sass or Less to define variables in CSS. While these tools are still useful, CSS Variables provide a native solution that is easier to use and more flexible.

To define a CSS Variable, you use the -- prefix followed by a name and a value. For example:

<style>
  :root {
    --primary-color: #007bff;
  }
  
  h1 {
    color: var(--primary-color);
  }
</style>

In this example, we define a variable called --primary-color and set its value to #007bff. We then use this variable to set the color of all h1 elements to the value of the variable.

One of the benefits of CSS Variables is that they can be updated dynamically using JavaScript. For example, you could change the value of the --primary-color variable based on user input or the time of day.

Here's an example of how you could use JavaScript to update a CSS Variable:

<style>
  :root {
    --primary-color: #007bff;
  }
  
  h1 {
    color: var(--primary-color);
  }
</style>

<button onclick="document.documentElement.style.setProperty('--primary-color', '#ff0000')">Change Color</button>

In this example, we define a button that, when clicked, changes the value of the --primary-color variable to #ff0000. This causes all h1 elements to update their color to the new value.

CSS Variables can also be used in conjunction with media queries to create responsive designs. For example:

<style>
  :root {
    --primary-color: #007bff;
  }
  
  h1 {
    color: var(--primary-color);
  }
  
  @media (max-width: 768px) {
    :root {
      --primary-color: #ff0000;
    }
  }
</style>

In this example, we define a variable called --primary-color and set its value to #007bff. We then use this variable to set the color of all h1 elements to the value of the variable. However, when the screen width is less than 768 pixels, we update the value of the variable to #ff0000, causing the color of all h1 elements to change.

CSS Variables are a powerful feature that can help make your CSS more maintainable and flexible. By defining reusable values, you can create a consistent design that is easy to update and modify.

References

Activity