CSS :root selector

CSS :root selector

This CSS pseudo-class matches any document’s root element. It chooses the parent of the highest-level inside the document DOM or tree.

An element of <html> is always a root element in HTML. But the :root selector is similar to the html selector. It is because both the elements target the same element, although the selector :root includes the higher specificity.

Syntax:

:root {  
     // CSS property  
 } 

Example:

<!DOCTYPE html>
 <html>
 <head>
 <title> :root selector </title>
 <style>
 :root
 {
  background: yellow;
  color: red;
  text-align: center;
 }
 </style>
 </head>
 <body>
 <h1> Welcome to this Page </h1>
 <h2> The :root selector is specified in this example. </h2>
 </body>
 </html> 

Output:

CSS root selector

Let’s try another method in which :root selector or html selector will implement simultaneously. If both these selector will implement within the specificity matter, the :root selector will win.

In the following example, we are using similar properties in both the selectors, i.e., :root selector and html selector. The :root selector properties will execute due to the higher specificity. Although a few properties are defined in the html selector but not in the :root selector, the html selector’s properties will work.

Example:

<!DOCTYPE html>
 <html>
 <head>
 <title> :root selector </title>
 <style>
 :root
 {
  background: violet;
  color: purple;
  text-align: center;
 }
 html
 {
  background: yellow;
  color: red;
  font-size: 30px;
 }
 </style>
 </head>
 <body>
 <h1> Welcome to this Page </h1>
 <h2> The html selector and :root selector is specified in this example. </h2>
 </body>
 </html> 

As we can define in the above illustration that the color and background-color properties both are defined in :root selector and also in the html selector. Although in the result, the :root selector properties will execute, due to the :root selector’s higher specificity.

Output:

CSS root selector