CSS Variables
Discover the power of CSS variables to make your stylesheets more dynamic, reusable, and easier to maintain.
What are CSS Variables?
CSS variables, formally known as **custom properties**, allow you to store specific values in a variable and reuse them throughout your stylesheet. This is incredibly useful for defining values that you use repeatedly, such as colors, fonts, or spacing. By changing a single variable, you can update every instance of that value across your entire website.
This is especially powerful for creating design systems, themes (like light and dark modes), and ensuring a consistent look and feel.
💡 Key Benefit
CSS variables reduce repetition and make your code more maintainable. You can easily update a global style by changing one variable instead of hunting down every instance of a color or font size.
Declaring and Using Variables
You declare a CSS variable by prefixing its name with two hyphens (--
). The best practice is to declare global variables inside the :root
pseudo-class, which makes them available to all elements on the page. To use a variable, you call it with the var()
function.
:root { --primary-color: #667eea; --font-family: 'Inter', sans-serif; } h1 { color: var(--primary-color); font-family: var(--font-family); }
Variable Scoping and Fallbacks
CSS variables are scoped, which means they are only available within the element you declare them on and its children. You can also provide a fallback value in the var()
function. This value will be used if the variable is not defined.
<!-- Local scope variable --> .card { --card-bg: #ffffff; background-color: var(--card-bg); } <!-- Using a fallback value --> h2 { color: var(--secondary-color, #333333); }
Live Example
This example demonstrates how CSS variables can be used to easily switch themes. The first card uses the default light theme, while the second one overrides the variables locally to create a dark theme.
Default Theme Card
This card uses the global variables set in the stylesheet. This is great for a consistent design.
Dark Theme Card
This card overrides the variables locally to achieve a different look. This shows the power of variable scoping.