Ask any question about CSS here... and get an instant response.
Post this Question & Answer:
How can I use CSS variables to create a responsive color scheme?
Asked on Apr 12, 2026
Answer
CSS variables, also known as custom properties, allow you to define reusable values throughout your stylesheet, making it easy to create a responsive color scheme. By defining these variables in the `:root` selector, you can ensure they are accessible globally and adjust them with media queries for responsiveness.
<!-- BEGIN COPY / PASTE -->
<style>
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--background-color: #ecf0f1;
}
body {
background-color: var(--background-color);
color: var(--primary-color);
}
.button {
background-color: var(--secondary-color);
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
}
@media (prefers-color-scheme: dark) {
:root {
--primary-color: #ecf0f1;
--secondary-color: #3498db;
--background-color: #2c3e50;
}
}
</style>
<body>
<button class="button">Click Me</button>
</body>
<!-- END COPY / PASTE -->Additional Comment:
- CSS variables are defined using the `--` prefix and can be accessed using the `var()` function.
- Media queries, like `@media (prefers-color-scheme: dark)`, allow you to change variable values based on user preferences or screen size.
- Using CSS variables helps maintain consistency and simplifies updates across your stylesheet.
- Ensure your color choices provide sufficient contrast for accessibility.
Recommended Links:
