Variables in Media Queries
CSS variables can be redefined within media queries to adapt styles dynamically based on the viewport size or other conditions. This enables responsive designs while maintaining a centralized and reusable set of styles.
Key Topics
- Basic Media Queries with Variables
- Scaling Variables Across Breakpoints
- Theme Switching with Media Queries
Basic Media Queries with Variables
Redefine CSS variables within media queries to change their values based on screen size.
<style>
:root {
--font-size: 16px;
}
@media (max-width: 600px) {
:root {
--font-size: 14px;
}
}
.text {
font-size: var(--font-size);
}
</style>
<div class="text">Resize the screen to see the font size change dynamically.</div>
Explanation: The --font-size
variable is redefined within the media query, reducing the font size for smaller screens.
Scaling Variables Across Breakpoints
Use variables to scale properties like padding, margin, or spacing across different breakpoints.
<style>
:root {
--padding-size: 20px;
}
@media (max-width: 768px) {
:root {
--padding-size: 15px;
}
}
@media (max-width: 480px) {
:root {
--padding-size: 10px;
}
}
.container {
padding: var(--padding-size);
}
</style>
<div class="container">Resize the screen to see the padding adjust dynamically.</div>
Explanation: The --padding-size
variable adjusts for different breakpoints, providing a consistent and scalable layout across devices.
Theme Switching with Media Queries
Combine CSS variables and media queries to implement theme switching, such as a light or dark mode based on system preferences.
<style>
:root {
--bg-color: #FFFFFF;
--text-color: #000000;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-color: #000000;
--text-color: #FFFFFF;
}
}
body {
background-color: var(--bg-color);
color: var(--text-color);
}
</style>
<div>This theme adjusts based on your system's color scheme settings.</div>
Explanation: The theme adjusts automatically based on the user’s system color scheme preference, using prefers-color-scheme
.
Key Takeaways
- Dynamic Variables: Redefine variables within media queries to adapt styles for different screen sizes or conditions.
- Responsive Design: Use variables for scalable properties like font size, padding, or spacing across breakpoints.
- Theme Integration: Combine media queries and variables to implement dynamic themes like light and dark modes.
- Maintainability: Centralize and reuse styles efficiently by leveraging CSS variables in media queries.
- Future-Proof: Media queries with variables enhance flexibility for evolving design requirements.