Nesting Media Queries
In 2020, yes!
Actually the accepted answer has been outdated for a long time now. I'm not even sure if it was technically correct even at the time of posting. Firefox has supported nesting since 2012 and Chrome since 2013 (source).
You should expect support from all major browsers now, of course with the usual exception of IE.
You can test it using the following HTML and CSS. Just open up dev panel in your browser and vary your viewport width.
<div id="abc">Example text</div>
#abc {
background: green;
}
/* width < 801px */
@media (max-width: 800px) {
#abc#abc {
background: red;
}
/* 500px < width < 801px */
@media (min-width: 500px) {
#abc#abc#abc {
background: yellow;
}
}
}
Alternatively, check out this codepen.
No. You need to use the and
operator and write that as two queries. You can, however, do this in SCSS, which will compile to CSS, but it will combine them by unfolding them and using the and
operator.
This is a common problem, and once I first wrote LESS or SCSS, I didn't ever want to go back to writing this long-hand.
Long-handed CSS:
@media (-webkit-min-device-pixel-ratio: 2) and (max-width: 768px) and (min-width: 320px),
(min-resolution: 192dpi) and (max-width: 768px) and (min-width: 320px) {
body {
border: 1px solid red;
}
}
@media (-webkit-min-device-pixel-ratio: 2) and (max-width: 320px),
(min-resolution: 192dpi) and (max-width: 320px) {
body {
border: 1px solid blue;
}
}
Nesting queries may work, but support varies across browsers.