Web Development - CSS Variables
CSS Variables
CSS Variables, also known as Custom Properties, let you store values such as colors, font sizes, and spacing in one place. You can reuse and update them easily across your entire stylesheet.
Syntax
CSS variables are defined using two dashes (--) followed by a custom name, and are accessed with the var() function.
Example
Defining and using a variable:
:root {
--main-color: coral;
--padding: 10px;
}
div {
background-color: var(--main-color);
padding: var(--padding);
}
Try it Yourself »
The :root selector defines global variables that can be used anywhere on the page.
Why Use CSS Variables?
- Keep your CSS consistent and organized.
- Make global style changes quickly.
- Reduce repetition and simplify maintenance.
- Support theme customization (light/dark modes, etc.).
Variable Scope
Variables can be defined globally (in :root) or locally within an element.
Example
Global vs local variables:
:root { --main-bg: lightblue; }
section { --main-bg: lightgreen; }
div.global { background: var(--main-bg); }
section.local div { background: var(--main-bg); }
Try it Yourself »
Local variables override global ones when defined within an element.
Using Fallback Values
You can specify a fallback value in case the variable is not defined.
If --text-color is not set, the text will default to black.
Changing Variables with JavaScript
You can update CSS variables dynamically using JavaScript to change themes or styles instantly.
Example
Changing a variable with JavaScript:
<button onclick="changeTheme()">Change Theme</button>
<script>
function changeTheme() {
document.documentElement.style.setProperty('--main-color', 'lightseagreen');
}
</script>
Try it Yourself »
CSS Variables and Inheritance
Variables are inherited just like normal CSS properties, meaning child elements can access variables from parent elements.
Practical Example: Theme Switching
You can use variables to create light and dark mode themes easily.
Example
Light and dark themes:
:root {
--bg-color: white;
--text-color: black;
}
body.dark {
--bg-color: #121212;
--text-color: #f1f1f1;
}
body {
background: var(--bg-color);
color: var(--text-color);
}
Try it Yourself »
Summary
- Store global variables inside
:root. - Define variables using
--namesyntax. - Access them with
var(--name). - Use meaningful names like
--main-coloror--font-size-large. - Group related variables (colors, spacing, typography).
- Use fallback values for safety.
- Change them dynamically with JavaScript for themes and interactivity.
Next, you'll start your CSS Project - putting together what you've learned to style a complete webpage.
Next » CSS Project: Style your Website