CSS Variables (Custom Properties)
CSS variables, also known as custom properties, allow you to store values in a central location and reuse them throughout your CSS. This feature enhances maintainability and readability by reducing the need for repetitive code.
CSS variables are defined using the --
prefix and are accessed using the var()
function.
Defining a CSS Variable:
- CSS variables are typically defined within a selector (commonly within the
:root
pseudo-class) so they can be accessed globally across the document. - Syntax:
--variable-name: value;
:root {
--primary-color: #3498db; /* Define a custom property for the primary color */
--secondary-color: #2ecc71; /* Define a custom property for the secondary color */
--font-size-large: 2rem; /* Define a custom property for large font size */
--spacing-unit: 16px; /* Define a custom property for spacing unit */
}
Using a CSS Variable:
- You can use the
var()
function to access the value of a CSS variable. - Syntax:
var(--variable-name, fallback)
body {
background-color: var(--primary-color); /* Use the custom property for the background color */
color: var(--secondary-color); /* Use the custom property for the text color */
font-size: var(--font-size-large); /* Use the custom property for font size */
margin: var(--spacing-unit); /* Use the custom property for margin */
}
Fallback Values:
- The
var()
function can accept a fallback value that is used if the variable is not defined. - Syntax:
var(--variable-name, fallback-value)
h1 {
color: var(--undefined-color, black); /* If --undefined-color is not defined, use black as the fallback */
}
Scope of CSS Variables
Global Scope:
- When defined under
:root
, a variable is accessible globally across the entire document.
:root {
--global-color: #333;
}
body {
color: var(--global-color); /* This can be accessed anywhere in the document */
}
Local Scope:
- Variables can also be defined within specific selectors, making them accessible only within those selectors or their children.
.container {
--local-background: #f9f9f9;
background-color: var(--local-background);
}
.container p {
background-color: var(--local-background); /* Accessible within the container and its children */
}
Overriding Variables
- CSS variables can be overridden by redefining them within a more specific selector.
:root {
--theme-color: #3498db;
}
.dark-theme {
--theme-color: #2c3e50; /* This overrides the global value within .dark-theme */
}
body {
background-color: var(--theme-color);
}