Processing styling rules based on certain criteria, such as viewport width, is achieved using the @media
conditional group rules. As of October 2018, all modern browsers support nested @media
queries.
What’s a @media query?
Here’s a simple example of a media query to make the text 10% bigger on devices with a screen (viewport) wider than 768px (the viewport width of the original iPad):
@media (min-width: 768px) {
p, div {
font-size: 1.1em;
}
}
This is a pretty self-explanatory snippet of code:
When the width is greater than 768 pixels relatively resize the font size of paragraph and div tags to 110% of their current size.
Cool, right? But what about if we also wanted to increase the font-size of div
tags by a different amount when the height is greater than 1024px? One solution is to use nested media queries.
What are nested @media queries?
Taking the problem described above, here’s an example of nested media queries to make the text within the paragraph
and div
tags 10% bigger on devices wider than 768px, but with a nested condition to apply an additional rule to div
tags when the viewport height is also at least 1024px:
@media (min-width: 768px) {
p, div {
font-size: 1.1em;
}
@media (min-height: 1024px) {
div {
font-size: 1.15em;
}
}
}
How about that?! The query is still pretty self-explanatory:
When the width is greater than 768 pixels relatively resize the font size of paragraph and div tags to 110% of the current size. However, if the height is greater than 1024 pixels relatively resize the font size of div tags to 115% of the current size.
Note: there are other ways to achieve this, without nesting the media queries, most obviously is by having separate query groups for paragraph
and div
tags.