Dynamic media/container queries using if()
Similar to the :nth-child() trick, we can use the if() condition and some calculation to implement the logic of media queries.
Instead of:
.container {
background; red;
@media (width < 450px) {
background: blue;
}
}
We can do:
@property --g {syntax: "<number>";inherits: true;initial-value: 0;}
.container {
--g: max(0,sign(100vw - 450px));
/* "screen wdith" < 450px : --g = 0
"screen wdith" > 450px : --g = 1
*/
background: if(style(--g: 1): blue; else: red);
}
Why reinvent the wheel with a more complex code? With this trick, you can easily update the 450px on the fly, as now it's part of a calculation. Something you cannot do with a classic media query!
And since the variable --g follows a Boolean logic, we can use it to perform other calculations as well:
@property --g {syntax: "<number>";inherits: true;initial-value: 0;}
.container {
--g: max(0,sign(100vw - 450px));
padding: calc(var(--g)*10px);
/* "screen wdith" < 450px : padding = 0px
"screen wdith" > 450px : padding = 10px
*/
}
Resize the screen in the below demo and see how things adjust based on the screen size without a single media query:
See the Pen Dynamic media queries with modern CSS by Temani Afif (@t_afif) on CodePen.
If we replace the 100vw with another value, we can get something different than media queries. If, for example, we use 100cqw, we can simulate container queries.
Here is the same demo, where this time the layout will adjust based on the width of the outer wrapper that you can resize:
See the Pen Dynamic container queries with modern CSS by Temani Afif (@t_afif) on CodePen.
⚠️ Limited support (Chrome only for now) ⚠️
More CSS Tips
- Why :is(::before,::after) doesn't work? Learn why the :is() selector doesn't work with pseudo-elements.
- 100 Ways to Center an element Horizontally and Vertically Explore all the possible ways to center a single element within a container.
- Responsive Infinite Logo Marquee Use modern CSS and a few lines of code to create an infinite scroll animation.
- How to place images around a circle A simple CSS code to correctly place a set of images (or any elements) around a circle.