CSS root
In CSS, :root
is a pseudo-class selector that matches the root element of the document, which is typically the <html>
element. The :root
pseudo-class is used to target and style the root element or set global CSS variables (custom properties) that can be used throughout the document.
The syntax for using :root
is as follows:
:root {
/* CSS properties and values */
}
Any CSS rules placed inside the :root
block will apply to the root element (usually the <html>
element). This can be useful for setting default styles, defining global CSS variables, or applying styles that are applied globally to the entire document.
Example:
:root {
font-size: 16px;
--primary-color: #007bff;
}
body {
color: var(--primary-color);
}
h1 {
font-size: 2em;
}
In this example, the :root
block sets a default font-size
of 16px
for the entire document and defines a global CSS variable --primary-color
with the value #007bff
. The body
element then uses this CSS variable to set the text color to the defined primary color. The h1
element is also styled, but it does not use the --primary-color
variable, so it will inherit the default font-size
specified for the :root
.
Using :root
to define global CSS variables can be very beneficial for maintaining consistent styles and easily changing properties across multiple elements in a web page. By defining variables at the root level, you can easily update the styles throughout the document by modifying the variable’s value once, rather than updating individual element styles.
It’s important to note that the :root
selector represents the root element of the document, which is typically the <html>
element. However, in some cases, such as when dealing with an iframe or when an XML document is being styled, the root element may differ from the <html>
element. Always verify the context in which you are using :root
to ensure it matches the intended root element of the document.