Nested Media Queries

I can’t seem to find any mention of this in the Media Queries Module specification, but apparently it’s allowed to nest media queries, as shared by Šime Vidas:

That’s … awesome! 🤯

Fiddling with it a bit more, turns out this snippet also works as expected:

@media not print {
	@media (min-width: 350px) {
		p {
			font-weight: bold;
		}
		@media (max-width: 1200px) {
			p {
				text-decoration: underline;
			}
		}
	}
	@media (max-width: 750px) {
		p {
			background: yellow;
		}
	}
}

You can play with this CodePen demo to try it yourself.

See the Pen
Nested Media Queries
by Bramus (@bramus)
on CodePen.

💁‍♂️ Don’t confuse Nested Media Queries with CSS Nesting, an upcoming feature of CSS, which allows you to nest selectors.

UPDATE: Thanks to reader Vadim Makeev for pointing out that support for nested @media blocks was added to Opera 12.50 back in 2012! Its syntax is defined in the CSS Conditional Rules Module specification.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Join the Conversation

2 Comments

  1. Wow. That is good to know! \o/

    I’ve done this many times in SCSS, always just assuming that it would be converted to a single statement for native CSS

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.