Convention for representing and interacting with objects in HTML, XHTML and XML documents.
CSS custom properties, often referred to as CSS variables, are entities defined by CSS authors that contain specific values to be reused throughout a document. They are set using custom property notation (e.g., --main-color: black;
) and are accessed using the var()
function (e.g., color: var(--main-color);
).
To use a CSS custom property, you first need to declare it. This is typically done in the :root
pseudo-class, which represents the root of the document.
:root { --main-bg-color: coral; }
Once declared, you can use the custom property throughout your stylesheet using the var()
function.
body { background-color: var(--main-bg-color); }
One of the key features of CSS custom properties is their ability to inherit. If you define a custom property on a parent element, it will be available on all child elements.
:root { --main-color: black; } body { color: var(--main-color); /* black */ } div { color: var(--main-color); /* black */ }
The scope of a CSS custom property is determined by where it is declared. If it's declared in the :root
, it's available globally. If it's declared inside a selector, it's available within that selector and its descendants.
:root { --global-color: black; } body { --body-color: white; color: var(--global-color); /* black */ } div { color: var(--body-color); /* white */ }
CSS custom properties can be easily overridden by simply redeclaring them within a specific scope.
:root { --main-color: black; } body { --main-color: white; color: var(--main-color); /* white */ } div { color: var(--main-color); /* white */ }
In the example above, --main-color
is redeclared in the body
selector, changing the value from black
to white
. This change affects the body
and any child elements, like the div
.
Understanding how to use CSS custom properties can greatly enhance your ability to create dynamic, adaptable stylesheets. They offer a powerful way to control and adjust your design in a consistent and efficient manner.