CSS :root | Style All Unstyled Elements

The CSS :root pseudo-class is used when we need to select the root element of an HTML document. The root element is always the HTML element. For example, the following code:

:root {background-color: #ccc;}

is same as:

html {background-color: #ccc;}

That is, both the above CSS codes perform the same specified task.

Select and Style All Unstyled HTML Elements—The :root

Consider the following code as an example demonstrating the styling of all unstyled HTML elements using CSS.

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      :root {color: blue;}
      span {color: red;}
   </style>
</head>
<body>

   <h2>The :root Selector</h2>
   <p>This para one.</p>
   <p>This is para two.</p>
   <span>@:root</span>
   
</body>
</html>
Output

The :root Selector

This para one.

This is para two.

@:root

In the above example, :root is a pseudo-class selector that selects an HTML document's root element. It is used in this case to make blue the default text color for the entire document.

Then the color is a CSS property used to color the text within an element. In this case, the root element's color is set to blue, and all other elements in the document will inherit this color by default.

Finally, the span is a CSS selector that targets any span elements in the HTML document.

When the above code is executed in a web browser, the default text color for the entire document is set to blue because the :root selector sets the color property for the root element of the document. However, the text color of the span element is overridden by the more specific span selector, which sets the color to red.

Therefore, the first two paragraphs within the body element will have blue text, while the span element will have red text. This demonstrates how CSS selectors can be used to apply styles to specific elements within an HTML document and how more specific selectors can override more general ones.

In the above example, since the element SPAN is selected and a style is applied to it, :root skips this element.

Note: The :root pseudo-class applies styles to all HTML elements that are not styled. Or, in other words, if I say, the :root is used to select all HTML elements that are not selected.

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!