root Selector

CSS :root selector in CSS is a pseudo-class that matches the root element of a document tree. In the case of HTML documents, :root represents the <html> element itself, so this selector is identical to the html element selector. But the :root selector have more specificity than HTML element selector.

Syntax

/* Selects the root element (<html>) of the document */:root{
// css variable declarations or properties
}

Declaring Global CSS variables

The main purpose of root selector is to declare variables in CSS. This will have a global access across every selectors in the stylesheet. Lets see an example.

Example

<!DOCTYPE html><html><head><style>
    :root {
    --main-color: blue;
    --secondary-color: white;
    }
    body {
    background-color: var(--main-color);
    }
    h1 {
    color: var(--secondary-color);
    }
&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;Welcome to CSS Root Example&lt;/h1&gt;&lt;p&gt; 
    This is an example of using CSS root to define and use 
    custom CSS variables.
&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *