What is the CSS :root Pseudo-Class Selector and how to use it
If you like styling your web pages and don't know about the :root {}
pseudo class, read this article! I’ll give you a different way to define base styles at one location to keep your CSS consistent, clean, and tidy.
When developing a website and using CSS, you can use :root {}
in your stylesheets to select the highest-level parent of the code. It is basically like using the html {}
selector in CSS. You can use them pretty much interchangeably to set up your page styles though there are some key differences.
Above is a screenshot of our page opened in a live server from visual studio and below is the CSS of what both the :root {}
and html {}
look like written out in visual studio with some examples. Both can make the page look the same as they do the same thing but do have a couple differences.
The main difference to know is their specificity. When I hover my mouse over the CSS class name, it tells me what the specificity is. The picture below is me hovering over both classes and revealing their specificity. You can see the :root
has a specificity of “0, 1, 0” or 10, while html
and has a specificity of “0, 0, 1” or 1.
Since they are so interchangeable, there are some common practices when using the two. When using the :root {}
class, it is best to use it for setting up global styles. You can write variables within the declarations of :root {}
with the CSS var()
function. Afterwards, you can use these variables other places in your stylesheets, like below in my styles.css file. When you need to update this variable value, make the changes at the variables in :root {}
and other CSS rules using the variables will pick up the changes.
When it comes to using the html {}
class, its best to add your styles to this selector and leave the global styles in the :root {}
selector. If you put styles inside the :root {}
class, they might not display correctly if your not using A high enough specificity in other classes. Or if you put global styles inside the html {}
class, you will clutter that section and make it harder to read your code.
Using the :root {}
class can be a very helpful tool in your box but only if used correctly. if used incorrectly, it can cause some headaches that you might not see right away. Now that shouldn't be a problem with your newfound knowledge of the :root {}
pseudo class, I encourage you to create something amazing using this concept as a foundation!