Home >Web Front-end >CSS Tutorial >CSS Variables – Streamlining Your Stylesheets
In this lecture, we will learn about CSS Variables (also known as custom properties) and how they help to simplify your code by allowing you to reuse values across your stylesheet.
CSS Variables enable you to store values such as colors, font sizes, or spacing in a central location and reuse them throughout your stylesheet. This makes your code more maintainable, as you can easily update the values in one place instead of searching through the entire stylesheet.
CSS Variables are defined with a -- prefix, and you can access them with the var() function.
CSS Variables are typically defined in the :root selector, which represents the top level of the document.
:root { --primary-color: #3498db; --secondary-color: #2ecc71; --font-size: 16px; } body { font-size: var(--font-size); color: var(--primary-color); } h1 { color: var(--secondary-color); }
In this example:
You can override CSS Variables within specific selectors to provide context-specific values.
:root { --primary-color: #3498db; } .dark-mode { --primary-color: #34495e; } body { color: var(--primary-color); }
In this example, the --primary-color is overridden when the .dark-mode class is applied. This allows you to switch between different color schemes (e.g., light mode and dark mode) effortlessly.
CSS Variables work well with media queries, allowing you to adjust values based on screen size.
:root { --font-size: 16px; } @media (max-width: 600px) { :root { --font-size: 14px; } } body { font-size: var(--font-size); }
In this example, the --font-size variable is reduced on smaller screens, making the text more readable on mobile devices.
You can provide fallback values for CSS Variables in case the variable is not defined or supported by the browser.
body { font-size: var(--font-size, 18px); }
Here, if --font-size is not defined, the browser will default to 18px.
One of the most powerful aspects of CSS Variables is that they can be manipulated using JavaScript, allowing you to create dynamic, interactive styles.
document.documentElement.style.setProperty('--primary-color', '#e74c3c');
In this example, the --primary-color variable is updated to a new color (#e74c3c) using JavaScript, which dynamically changes the style of the page.
CSS Variables offer a flexible way to manage your styles, improve code maintainability, and enable dynamic updates. By incorporating CSS Variables into your workflow, you can streamline your development process and create more maintainable, scalable stylesheets.
Ridoy Hasan
The above is the detailed content of CSS Variables – Streamlining Your Stylesheets. For more information, please follow other related articles on the PHP Chinese website!