1.1 What are CSS Variables?
CSS variables, also known as custom properties, are variables declared in CSS, which can be used to store values such as colors, sizes, fonts, and other CSS attributes. They provide effective ways to improve the flexibility and maintainability of styles on web pages.
What are CSS Variables?
CSS variables are variables that can hold CSS property values and be reused in various parts of styles. They are defined using a double dash (--), and can be set in any selector, but are most often defined in the root selector :root
to make them available throughout the document.
Example:
:root {
--main-color: #3498db;
--secondary-color: #2ecc71;
--font-size: 16px;
}
Main Features of CSS Variables:
- Reusability: CSS variables allow you to define a value once and use it multiple times in different parts of the CSS code. This helps avoid duplication and makes style management easier.
- Flexibility: The values of CSS variables can change depending on conditions, such as element states or media queries. This allows for more adaptive and dynamic styles.
- Inheritance: CSS variables are inherited from parent elements to child elements, simplifying style management and organization.
- Manageability: Using variables makes code maintenance easier, as changes to variable values are automatically reflected in all elements using those variables.
1.2 Examples of CSS Variable Usage
Example of Using CSS Variables in JavaScript:
document.documentElement.style.setProperty('--main-color', '#e74c3c');
Example 1: Defining and Using Variables
:root {
--main-bg-color: #f0f0f0;
--main-text-color: #333;
--primary-color: #3498db;
}
body {
background-color: var(--main-bg-color);
color: var(--main-text-color);
}
a {
color: var(--primary-color);
}
a:hover {
color: darken(var(--primary-color), 10%);
}
<body>
<p>This is a paragraph.</p>
<a href="#">This is a link</a>
</body>
Explanation:
- In this example, three variables are defined:
--main-bg-color
,--main-text-color
, and--primary-color
- These variables are used to set the background color, text color, and link color
1.3 Changing Variable Values in JavaScript
In this example, variables are used to set the theme of the page. When the button is clicked, the variable values change, resulting in a change of the background and text color:
:root {
--main-bg-color: #f0f0f0;
--main-text-color: #333;
}
body {
background-color: var(--main-bg-color);
color: var(--main-text-color);
}
<button id="toggle-theme">Toggle Theme</button>
<p>This is a paragraph.</p>
document.getElementById('toggle-theme').addEventListener('click', () => {
const root = document.documentElement;
if (root.style.getPropertyValue('--main-bg-color') === '#f0f0f0') {
root.style.setProperty('--main-bg-color', '#333');
root.style.setProperty('--main-text-color', '#f0f0f0');
} else {
root.style.setProperty('--main-bg-color', '#f0f0f0');
root.style.setProperty('--main-text-color', '#333');
}
});
GO TO FULL VERSION