Theme Example
This is a paragraph with the current theme applied. Notice how all colors change when you switch themes.
Learn how to use and reuse CSS custom properties for dynamic styling
CSS Custom Properties (also known as CSS Variables) allow you to store specific values to be reused throughout your 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);
).
This allows for more maintainable and flexible CSS, especially for properties that are repeated throughout your stylesheet.
Here are some examples of basic custom properties defined in the :root
scope and used throughout different elements:
One of the most powerful uses of CSS Custom Properties is for theme switching. By changing a few variables, you can completely transform the look of your website:
This is a paragraph with the current theme applied. Notice how all colors change when you switch themes.
CSS Custom Properties can be redefined within media queries, making responsive design more maintainable:
This container changes its width, font size, and padding based on the viewport size. Resize your browser to see the effect.
You can use the calc()
function with custom properties to create dynamic calculations:
This element has padding and margin that are calculated based on a base size and multiplier.
You can provide fallback values for custom properties that might not be defined:
This element uses fallback values for undefined custom properties.
CSS Custom Properties can be manipulated with JavaScript, making them perfect for dynamic styling:
This element's style can be changed using the controls above.