Defining variables
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.
Exercise Define both global and local variables
Inside :root, define --renk with value #2563eb. Then, inside a .bayrak selector, redefine --renk with value #dc2626.
Show example solution
open two separate selectors, put a --renk definition in each.
Example solution:
:root {
--renk: #2563eb;
}
.bayrak {
--renk: #dc2626;
}
Test yourself
-
Which is a correct variable definition?
:root { ? }- color: #2563eb;
- var(--color): #2563eb;
- --color: #2563eb;
- --color = #2563eb;
Show answer
--color: #2563eb; — Correct! --color: #2563eb; starts with two dashes and uses a colon for the value.
-
Add a variable to :root
:root { ____: 1.5rem; }Show answer
:root { --root-size: 1.5rem; } -
Match scope
- Global variable
- defined in :root
- Local variable
- defined on element
- Descendants
- inherit the scope
- Same name clash
- local wins