The :root Selector for Global Variables
What you'll learn: How to use the :root selector to create global CSS custom properties that are accessible throughout your entire stylesheet.
What is :root?
The :root pseudo-class selector targets the root element of your document—in HTML, that's the <html> element. While you could just write html {}, :root is more specific and is the conventional place to define global CSS custom properties (variables).
Think of :root like a "headquarters" for your variables. Just as a company's headquarters makes decisions that affect all branch locations, custom properties defined in :root are available everywhere in your stylesheet.
Why Use :root for Variables?
When you declare custom properties inside :root, they become global—any element on your page can access them. This is because of CSS's inheritance system: child elements inherit custom properties from their ancestors, and :root is the ultimate ancestor of everything.
:root {
--primary-color: #3498db;
--spacing-unit: 1rem;
--font-main: 'Arial', sans-serif;
}
/* Now use these anywhere */
.button {
background-color: var(--primary-color);
padding: var(--spacing-unit);
font-family: var(--font-main);
}
.header {
color: var(--primary-color);
margin-bottom: calc(var(--spacing-unit) * 2);
}
Both .button and .header can access those variables because they're defined at the root level—the top of the family tree.
Scope Inheritance
Custom properties follow the cascade. Variables defined in :root cascade down to all descendants. You can also override them locally within specific selectors for more targeted control, but we'll explore that pattern in future lessons.
Key Takeaway: Use :root to define global custom properties that are accessible throughout your entire stylesheet, creating a centralized system for managing design tokens like colors, spacing, and fonts.