Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Style the document's root element with CSS
The CSS :root pseudo-class selector targets the document's root element. In HTML documents, this is the <html> element. It's commonly used to define CSS custom properties (variables) and global styles.
Syntax
:root {
property: value;
}
Example 1: Basic Root Element Styling
The following example applies background and text color to the root element −
<!DOCTYPE html>
<html>
<head>
<style>
:root {
background: blue;
color: white;
font-family: Arial, sans-serif;
}
h1 {
text-align: center;
margin-top: 50px;
}
p {
text-align: center;
font-size: 18px;
}
</style>
</head>
<body>
<h1>Document Root Styling</h1>
<p>This entire page has a blue background with white text.</p>
</body>
</html>
A page with blue background and white text appears. The heading and paragraph are centered and clearly visible against the blue background.
Example 2: CSS Custom Properties with :root
The :root selector is most commonly used to define CSS custom properties (variables) −
<!DOCTYPE html>
<html>
<head>
<style>
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--font-size: 16px;
--border-radius: 8px;
}
.card {
background-color: var(--primary-color);
color: white;
padding: 20px;
border-radius: var(--border-radius);
font-size: var(--font-size);
margin: 20px auto;
width: 300px;
text-align: center;
}
.button {
background-color: var(--secondary-color);
padding: 10px 20px;
border: none;
border-radius: var(--border-radius);
color: white;
font-size: var(--font-size);
margin-top: 10px;
}
</style>
</head>
<body>
<div class="card">
<h3>Custom Properties Demo</h3>
<p>This card uses CSS variables defined in :root</p>
<button class="button">Click Me</button>
</div>
</body>
</html>
A centered blue card with white text appears, containing a heading, paragraph, and a green button. All styling uses variables defined in the :root selector.
Key Benefits
| Feature | Description |
|---|---|
| Global Variables | Define reusable values across the entire stylesheet |
| Higher Specificity | Has higher specificity than regular element selectors |
| Consistency | Ensures consistent styling throughout the document |
Conclusion
The :root selector is essential for defining global styles and CSS custom properties. It provides a central location for managing design tokens and ensures consistent styling across your entire website.
Advertisements
