CSS Variables (Custom Properties)
CSS Variables, also known as custom properties, allow you to store values in a single place and reuse them throughout your CSS. This makes it easier to maintain and update your styles, especially when you need to make global changes.
Defining and Using CSS Variables
CSS Variables are defined using the `--` prefix and are accessed using the `var()` function.
/* Defining CSS Variables */
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--font-size: 16px;
}
/* Using CSS Variables */
body {
color: var(--primary-color);
font-size: var(--font-size);
}
button {
background-color: var(--secondary-color);
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
font-size: var(--font-size);
}
Advantages of CSS Variables
- Reusability: Define a value once and reuse it multiple times throughout your CSS.
- Maintainability: Easily update a variable's value, and it will automatically reflect everywhere the variable is used.
- Theme Management: CSS Variables can be used to create themes by switching out variables for different themes (e.g., dark mode vs. light mode).
- Dynamic Changes: Variables can be updated dynamically using JavaScript, allowing for real-time style changes based on user interaction.
Practical Examples of CSS Variables
Example: Theming with CSS Variables
/* Light Theme */
:root {
--background-color: #ffffff;
--text-color: #333333;
}
/* Dark Theme */
body.dark-theme {
--background-color: #333333;
--text-color: #ffffff;
}
body {
background-color: var(--background-color);
color: var(--text-color);
}
This example demonstrates how you can use CSS Variables to easily switch between a light and dark theme.
Example: Media Queries with CSS Variables
/* Base font size */
:root {
--font-size: 16px;
}
@media (min-width: 768px) {
:root {
--font-size: 18px;
}
}
@media (min-width: 1024px) {
:root {
--font-size: 20px;
}
}
body {
font-size: var(--font-size);
}
This example shows how to adjust the base font size using CSS Variables within media queries.
Understanding Scope and Inheritance
CSS Variables are scoped. They can be defined globally (e.g., in the `:root` selector) or locally within specific elements. Child elements inherit CSS Variables, but they can also override them by redefining the variable.
/* Global variable */
:root {
--primary-color: #3498db;
}
/* Local variable override */
.card {
--primary-color: #e74c3c;
background-color: var(--primary-color);
padding: 20px;
border-radius: 10px;
color: white;
}
CSS Variable Fallbacks
The `var()` function can include a fallback value that is used if the variable is not defined. This ensures your styles work even if the variable is missing.
/* Using fallback value */
body {
color: var(--undefined-color, black);
}
In this example, if `--undefined-color` is not defined, the text color will default to black.