Academy / Advanced Level: HTML and CSS
CSS Variables (Custom Properties)
Global vs. Local Variables
CSS Variables can be defined globally or locally. Variables defined in the :root selector are global, meaning they can be used anywhere in the stylesheet. However, you can also define local variables that are scoped to specific elements or components.
Global Variables:
When defined under the :root selector, variables are available globally throughout the entire document.
:root {
--global-color: #ff5733;
}
Local Variables:
Local variables are scoped to specific elements or selectors and override global variables within that scope.
.section {
--section-color: #2980b9; /* Local variable for this section only */
background-color: var(--section-color);
}
Example:
:root {
--primary-color: #3498db; /* Global variable */
}
.section {
--primary-color: #8e44ad; /* Local variable (overrides global within .section) */
background-color: var(--primary-color);
}
In this example:
- The global variable
--primary-coloris blue. - Inside the
.sectionclass,--primary-coloris redefined as purple, overriding the global value.