Defining variables
- CSS course
- Intermediate
- Lesson 71/98
- 5 min
Learn to define variables on :root and elements.
The :root selector
:root selects the document's root element; in HTML that is the html tag. Variables defined here are in the global scope: every element on the page can see and use them.
That's why brand colors, spacing values, and other everywhere-needed variables go inside :root. One source, one update point.
Definition syntax
A variable is written like a normal CSS declaration: name, colon, value, semicolon. The only difference is the name starts with two dashes. This structure is called a custom property.
Example: --color: #2563eb;, --space: 16px;, --size: 1.25rem;. The value can be a color, a length, or even another variable; --color-accent: var(--color); is valid.
Scope
A variable's scope is limited to the element where it is defined. A variable in :root applies everywhere, while a variable inside a button only applies to that button and its descendants.
A local variable shadows a global one with the same name. This lets you reuse one name with different values in different components; no clash.
Practice Define both global and local variables
Inside :root, define --renk with value #2563eb. Then, inside a .bayrak selector, redefine --renk with value #dc2626.
Starter code
/* Inside :root, write --renk: #2563eb; */
/* Inside .bayrak, write --renk: #dc2626; */Sample solution
:root {
--renk: #2563eb;
}
.bayrak {
--renk: #dc2626;
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a correct variable definition?
:root {
?
}- color: #2563eb;
- --color: #2563eb; Correct answer
- var(--color): #2563eb;
- --color = #2563eb;
Explanation: --color: #2563eb; starts with two dashes and uses a colon for the value.
2 Add a variable to :root
:root {
____: 1.5rem;
}
:root {
--root-size: 1.5rem;
}
Explanation: --root-size starts with two dashes.
3 Match scope
| Term | Meaning |
|---|---|
Global variable |
defined in :root |
Local variable |
defined on element |
Descendants |
inherit the scope |
Same name clash |
local wins |