Academy / Advanced Level: HTML and CSS
CSS Variables (Custom Properties)
Overriding and Cascading CSS Variables
CSS Variables follow the cascading rules of CSS, meaning variables can be overridden in more specific contexts. The most specific rule will always take precedence, following the same principles as specificity and inheritance.
Example of Cascading and Overriding:
:root {
--font-size: 18px;
}
p {
font-size: var(--font-size); /* Default size */
}
.section p {
--font-size: 24px; /* Override for p elements inside .section */
font-size: var(--font-size);
}
In this example:
- All
<p>elements have a default font size of18px, defined in the global:rootscope. - However, within
.section, the<p>elements have a font size of24px, overriding the global value.