Colors in :root

Hi,

When looking at other people’s projects I often see this in the css:

:root {
–main-white: #f0f0f0;
–main-red: #be3144;
–main-blue: #45567d;
–main-gray: #303841;
}

Can anyone explain to me what these colors do and what :root means? Thanks!

Hi @clare.parkes !

It is a pseudo class that represents the root element of the document.

What you are looking at are css variables.
You can create your own css variables and reuse them throughout these rest of your stylesheet.

The is helpful if you need to reuse the same colors over and over again.

Instead of this.

.header {
   background-color: #ff0000;
}

.quotes-text {
  color:#ff0000;
}

etc..

You can cut down on repetition by using css variables.
You declare them once and reuse them.

.header {
   background-color: --main-red;
}

.quotes-text {
  color--main-red;
}

In larger projects, it is also helpful to have a seperate colors files with all of your css variables declared and then you can reuse then in multiple stylesheets.

Here is an example project I did for an article, where I created a seperate css colors file and imported that color file into other stylsheets.

The syntax will look a little different because I am using sass, but the basic concept is still the same.

Here is the colors file and here is an example of me using that colors file in another stylesheet

Hope that helps!

3 Likes

Hi @clare.parkes ,

The :root pseudo-class represents an element that is the root of the document. In HTML, this is always the HTML element, except that its specificity is higher…

:root can be useful for declaring global CSS variables:

:root {
  --main-color: hotpink;
 --main-bg-color: brown;
}

You can learn more about CSS variables in this challenge :

https://www.freecodecamp.org/learn/responsive-web-design/basic-css/use-css-variables-to-change-several-elements-at-once

I hope this helps :wink:

2 Likes

Docs for reference

Thanks I vaguely remember doing thst penguin challenge but it was a while ago

1 Like

Thanks these links are very helpful!

That is very helpful and clearly explained i will definetly use these in my next project

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.