CSS Variables

CSS (Cascading Style Sheets) is a powerful tool used to style and format the appearance of web pages. One of the key features of CSS is the use of variables, which allow developers to define reusable values that can be used throughout their stylesheets. In this article, we will explore the concept of CSS variables and provide examples of how they can be used.

CSS variables, also known as custom properties, are defined using the “–” prefix followed by a name. For example, “–primary-color” or “–font-size”. These variables can then be assigned values that can be referenced later in the stylesheet. Let’s dive into some examples to better understand how CSS variables work.

Example 1: Defining and Using a CSS Variable
“`css
:root {
–primary-color: #007bff;
}

h1 {
color: var(–primary-color);
}
“`
In this example, we define a CSS variable called “–primary-color” and assign it the value of “#007bff”, which is a shade of blue. We then use this variable to set the color of the “h1” element. By using the “var()” function, we can reference the value of the variable and apply it to the desired property.

Example 2: Using CSS Variables in Multiple Declarations
“`css
:root {
–primary-color: #007bff;
–secondary-color: #6c757d;
}

.button {
background-color: var(–primary-color);
color: var(–secondary-color);
}
“`
In this example, we define two CSS variables, “–primary-color” and “–secondary-color”, and assign them values. We then use these variables to set the background color and text color of a button element with the class “button”. By using CSS variables, we can easily change the color scheme of our website by modifying the values of these variables.

Example 3: Modifying CSS Variables with JavaScript
“`css
:root {
–primary-color: #007bff;
}

.button {
background-color: var(–primary-color);
}

.button:hover {
–primary-color: #ff0000;
}
“`
In this example, we define a CSS variable called “–primary-color” and assign it the initial value of “#007bff”. We then use this variable to set the background color of a button element. However, when the button is hovered over, we modify the value of the “–primary-color” variable to “#ff0000” (red) using JavaScript. This allows us to dynamically change the appearance of elements based on user interactions.

CSS variables provide a convenient way to centralize and reuse values in a stylesheet. They offer flexibility and make it easier to maintain and update the styles of a website. By using CSS variables, developers can create more consistent and modular stylesheets.

In conclusion, CSS variables are a powerful feature of CSS that allow developers to define reusable values and easily modify the appearance of web pages. By using the “var()” function, CSS variables can be referenced and applied to various properties. They provide flexibility, maintainability, and enhance the overall efficiency of CSS development.

Scroll to Top