DEV Community

Raj
Raj

Posted on

CSS :root Selector

What is :root?
:root in CSS. At first I was confused about why we use :root instead of simply writing CSS normally.

In :root represents the main element of a webpage. It is commonly used to store CSS variables that we want to use throughout our website.

Why do we use :root?

The main reason is to keep our commonly used values in one place.

Example

instead of writing the same colors again and again, we can create a variable:

:root {
--bg-main: #ffffff;
--text-main: #1a1a1a;
--accent: #6200ee;
}

Then we can use those variables anywhere in our CSS:

body {
background-color: var(--bg-main);
color: var(--text-main);
}

button {
background-color: var(--accent);
}

How does it work?

The :root section stores the values.

The --bg-main, --text-main and --accent names are CSS variables.

When we use var(--accent), CSS takes the value stored inside --accent.

So the basic flow is:

:root → Store values → var() → Use values

Example

This becomes especially useful when creating a website with different color.

For example, we can have one set of variables for a colors and another set for a colors.

:root {
--bg-main: white;
--text-main: black;
--accent: purple;
}

Later we can change these values for a colors.

This makes our CSS easier to manage because we don't have to change every element individually.

Top comments (0)