CSS Custom Variables
What are CSS Custom Variables?
Imagine you are decorating a large hotel. You decide to use a specific shade of royal purple for the curtains, bedsheets, carpets, and towels. If you write down the exact color name in every single room's order form, and then the owner decides to change the color to navy blue, you have to find and rewrite every single form. Instead, you declare a code-word:[Theme Color] = Royal Purple. In the forms, you just write Color: Theme Color. Now, if the owner wants blue, you change the code-word once at headquarters!In CSS, CSS Custom Properties (Variables) store styling values that you can reuse throughout your stylesheet. They are defined starting with double dashes (--) and referenced using the var() function:
--primary-color: purple; โ Declares the variable.color: var(--primary-color); โ References and applies the variable.Why does it matter?
CSS variables are the backbone of modern web design systems. They allow you to define theme colors, spacing parameters, and typography sizes in a single central place (usually the:root pseudo-class representing the entire document). If you want to build a "Dark Mode" toggle, you just rewrite your color variables inside a .dark class block!
Syntax Breakdown
:root { --main-color: #333; } โ Declares variable on global scope.body { background-color: var(--main-color); } โ Applies the variable.Common Mistakes
primary-color: purple; or trying to reference it using var(primary-color) will fail. The browser requires the double dashes -- to recognize it as a custom variable..card class rule, it cannot be accessed by elements in the footer. To make a variable global, always declare it inside :root!Quick Reference
--varname โ Syntax to declare custom properties.var(--varname) โ Function to apply variable values.:root โ Global selector target representing the document root.Your Task
Define the variable `--primary-color` inside the `:root` block, setting its color value to `purple`.
index.html
Type code above to start the lesson.
Live Preview