Academy / Advanced Level: HTML and CSS
CSS Variables (Custom Properties)
What Are CSS Variables?
CSS Variables are defined using the -- prefix, followed by the name of the variable. These variables are then accessed using the var() function.
Defining Variables:
Variables are usually defined within a selector, often within the :root selector for global scope, but you can define them in any context (local scope).
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--font-size: 16px;
--padding: 20px;
}
Using Variables:
You can reference and use these variables in any property by using the var() function.
body {
background-color: var(--primary-color);
font-size: var(--font-size);
padding: var(--padding);
}
h1 {
color: var(--secondary-color);
}
In this example, the variables --primary-color, --secondary-color, --font-size, and --padding are used throughout the stylesheet, allowing easy maintenance and consistent styling.