CSS Media Queries: Responsive Layouts with Modern Syntax
A CSS media query applies styles only when the user’s device or browser matches a condition you write, such as a viewport at least 40rem wide, a dark colour scheme, or a preference for reduced motion. You write it as @media (condition) { … }, and it is the mechanism behind every responsive layout. This guide covers the syntax you should use today, the conditions worth knowing, and when to reach for a container query instead.
The original version of this tutorial was about swapping stylesheets for the iPhone, the iPad and old versions of Internet Explorer. Those hacks are gone. Media queries now describe the viewport and the user’s preferences, not a particular device, and they sit next to container queries, which let a component respond to the space it is given.
The basic shape of a media query
A media query has an optional media type (screen, print) and one or more conditions in parentheses. For most layout work you can drop the media type entirely, since the condition is enough.
/* Styles for viewports 40rem (640px at default font size) and wider */
@media (width >= 40rem) {
.cards {
grid-template-columns: 1fr 1fr;
}
}
The same rule works on a <link> element when you want to split CSS into files. The browser still downloads a non-matching stylesheet, but at low priority and without blocking rendering.
<link rel="stylesheet" href="wide.css" media="(width >= 64rem)">
<link rel="stylesheet" href="print.css" media="print">
Make sure every page has the viewport meta tag, or phones will pretend to be roughly 980px wide and none of your width queries will do what you expect:
<meta name="viewport" content="width=device-width, initial-scale=1">
Use range syntax instead of min-width and max-width
The older min-width and max-width prefixes still work and will keep working. Range syntax, written with comparison operators, is easier to read and removes a classic off-by-one bug: with max-width: 600px and min-width: 600px both matching at exactly 600px, and fractional widths slipping between max-width: 599px and min-width: 600px.
@media (width >= 40rem) { /* 40rem and up */ }
@media (width < 40rem) { /* strictly below 40rem */ }
@media (40rem <= width < 64rem) { /* tablet band */ }
The original tutorial combined two conditions with and to target a band. Range syntax handles that in one expression, as the third line above shows. Range syntax is supported in all current major browsers (check the Baseline badge on MDN’s media queries page if you support older ones).
Write mobile first, and use rem for breakpoints
Write the small-screen styles with no query, then add width >= queries that enhance the layout as space grows. Mobile-first CSS is shorter, because the default state needs no overrides, and it fails gracefully if a query does not match.
Express breakpoints in rem or em rather than pixels. In media queries both units are relative to the browser’s default font size, not your CSS, so a visitor who raises their default text size gets the larger layout at a proportionally wider viewport. Pixel breakpoints ignore that setting, which is why zoomed text so often breaks them.
Pick breakpoints where your content breaks, not where a popular phone happens to sit. Resize the window until a line is too long or a column too cramped, and put the breakpoint there. Our guide to setting breakpoints in responsive design covers that process in more detail.
A working example
This page uses three tiers. It stays single-column on small screens, moves to two columns at 40rem, adds a sidebar at 64rem, and shows a menu button only below 40rem.


.page { display: grid; gap: 1.5rem; padding: 1rem; }
.cards { display: grid; gap: 1rem; }
nav ul { display: none; }
@media (width >= 40rem) {
.page { padding: 2rem; }
.cards { grid-template-columns: 1fr 1fr; }
.menu-btn { display: none; }
nav ul { display: flex; gap: 1.25rem; }
}
@media (width >= 64rem) {
.page { grid-template-columns: 16rem 1fr; }
header { grid-column: 1 / -1; }
aside { display: block; }
}
Notice that the base styles are the phone layout and each query only adds. Hiding the navigation links with display: none removes them from the accessibility tree too, so the menu button must open a real, keyboard-reachable list. For the pattern itself, see our responsive navigation menu tutorial or the responsive navbar snippet.
Because the queries are plain CSS, you can nest them inside the rule they modify. CSS nesting is supported in current browsers, and it keeps a component’s responsive behaviour in one place:
.cards {
display: grid;
gap: 1rem;
@media (width >= 40rem) {
grid-template-columns: 1fr 1fr;
}
}
Container queries: respond to the component’s space
A media query only knows the viewport. A card dropped into a narrow sidebar, a wide main column or a three-up grid sees the same viewport in all three, so viewport queries cannot give it the right layout in each. Container queries solve this by measuring the nearest ancestor you mark as a container.
.slot { container-type: inline-size; }
.card {
display: grid;
gap: .5rem;
}
@container (width >= 28rem) {
.card {
grid-template-columns: 10rem 1fr;
align-items: center;
}
}
In the demo above, the first card sits in a wide slot, so it switches to a horizontal layout. The two cards below sit in half-width slots and stay stacked, even though the viewport is identical. An element cannot query itself, which is why the wrapper (.slot) carries container-type and the card is its child.
A practical rule: use media queries for page-level decisions such as columns, navigation and sidebar, and container queries for components that get reused in different places, such as cards, pricing blocks and widgets. Size container queries are supported in all current major browsers. Style queries and scroll-state queries are newer, so check MDN’s Baseline badges before you rely on them. Our product card grid snippet is a good candidate to convert.
Media features worth using beyond width
Width is only one condition. These features let you adapt to the person, not just the screen:
| Feature | Use it to | Example |
|---|---|---|
prefers-reduced-motion |
Remove or tone down animation for people who ask the OS for less motion | @media (prefers-reduced-motion: reduce) |
prefers-color-scheme |
Provide a dark theme that follows the system setting | @media (prefers-color-scheme: dark) |
hover and pointer |
Show hover effects only where a mouse exists; enlarge targets for touch | @media (hover: hover) and (pointer: fine) |
resolution |
Serve sharper assets on high-density screens | @media (resolution >= 2dppx) |
orientation |
Adjust for portrait or landscape | @media (orientation: landscape) |
print |
Style printed pages | @media print |
The first two are the ones most sites still miss. A dark theme needs only a handful of custom properties:
:root {
color-scheme: light dark;
--bg: #f6f7fb;
--ink: #1b1f2a;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #12141c;
--ink: #eceef5;
}
}
body { background: var(--bg); color: var(--ink); }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: .01ms !important;
transition-duration: .01ms !important;
scroll-behavior: auto !important;
}
}
For image-heavy pages, do not use resolution queries to swap background images when you can use srcset and <picture> in the markup. The browser then picks the right file and you avoid extra CSS.
What to stop doing
- Device-specific queries. Rules such as
max-device-width: 480px,-webkit-min-device-pixel-ratio: 2or “for iPad” stylesheets target hardware that no longer defines your audience. Thedevice-widthanddevice-heightfeatures are deprecated in the spec; usewidthandheight, which describe the viewport. - JavaScript polyfills for old Internet Explorer. Internet Explorer is retired and the plugins that faked media queries for it are unnecessary.
- Vendor prefixes. Use the standard
resolutionfeature withdppx, not-webkit-min-device-pixel-ratio. - Breakpoints for every device. Two or three breakpoints, combined with fluid grids,
clamp()and container queries, cover more screens than a long list of device widths. - Using queries as a performance tool. The original article made the same point: a media query changes presentation, not weight. A hidden image may still download. Use
srcset,sizesandloading="lazy"to reduce what is sent.
Sample sites: what to look for
The 2010 version of this article showed four sites whose layouts reshaped as you resized the window. Most of those designs have since been redesigned, so rather than a list that will rot, here is a more useful exercise. Open any site you admire, open browser DevTools, toggle the device toolbar and drag the width. Then, in the Styles panel, look for the breakpoints it uses. You will usually find three things: a small number of width breakpoints, content that reflows without fixed pixel widths, and images set to max-width: 100%. If you want to go further, our responsive design in 3 steps and responsive column layouts tutorials show the layout side in practice.
Quick checklist
- Add the viewport meta tag to every page.
- Write the small-screen layout first, with no query.
- Add
@media (width >= …rem)queries where the content needs them. - Use container queries for components that appear in more than one context.
- Respect
prefers-reduced-motionandprefers-color-scheme. - Gate hover-only effects behind
(hover: hover). - Test by resizing, zooming text and using a real phone.
Excellent tutorials and thanks for the tips about the iphone resolution and ipad orientation…
Nice post!
@Brandon
It’s not a typo, he’s referring to the previous CSS version, 2.
Does the orientation hook work on iPhones as well? Or just iPads?
7. Eric – No, the orientation hook only works on the iPad. :-(
Nice examples that you’ve got here.
It would be great if you could let anyone download it. As you did in the past.
@Alojamento Web – To download the demo, go to File > Save Page As.
Great post and another great tool to add to your CSS arsenal.
Excellent post. It will be interesting to apply to fluid HTML5/CSS3 layout on my new site launch in September.
Great article. Mobile design is definitely not a cosmetic only feature anymore and with the growing market of smartphones, better start doing it by default i’d say.
Very helpful, can’t wait to utilize this. I wonder if you could target specific devices like the iphone/pad just by using CSS now…?
Very well written article, thank you. I liked the examples you provided, makes it easy to follow along.
It’s just to bad that IE as usually won’t support these kind of things. I have great hopes for IE9 though, once it’s released!
Great info. Media queries is a nice addition to CSS that saves us a lot of time and effort in making the website more user-friendly. The provided demo is very useful.
Great Great Great. Your CSS tutorials are the best!
Hi,
Certainly I have off topic question. I can see that web designers struggling for cross browser compatibility. My question is, is CSS3 still usable for our website. We still have lots of people still using Internet Explorer 6 and other non-upgraded browser version.
I don’t think older version browsers supports CSS3. How much practical it is to design your website in CSS3?
Regards,
Webdezine Blog
CSS 3 is pretty amazing! These media queries will certainly make life easier applying stylesheets to different browser sizes and mobile browsers. The iphone one is a good idea with the two orientations – simples. :)
That’s useful, too bad CSS3 is only on modern browsers, I have tested many CSS3 codes on older browsers and the page gets converted into a mess, I guess we would have to wait until most people upgrade their browsers.
Thanks for sharing this. I have written it down on my notebook. IE is a mess so we have to wait for IE supporting this.
I just went to the demo web page on my phone (Samsung Gravity, smaller than an iPhone). Unfortunately all the colored boxes were lit up at once…so something went wrong. It seems the entire web design community is struggling to find a working solution. Surely there must be a way to check the screen size on non-Apple (and thus, non-Safari) devices?
Yes, with css3 and html5 ,we can imply many effect easily.
CSS 3 is going to help no end when developing websites! I wonder if IE will support this anytime soon?
great post.
Now THIS is called story.now i am waiting for another
Very informative and inspirational article! The same goes for the entire site. I’ve added you to my “must read weekly” right along with the likes of Alist Apart. Please keep up the good work. We budding web developers need out heroes!
this css is very good and it is beautiful theme
I will take this for my websites
Nice CSS
but it not appropiate with my website
Great info. The provided demo is very useful.
Searh jobs
12,257,378 new jobs in the last 7 days
inpeed.com
I was reading something else about this on another blog. Interesting. Your position on it is diametrically contradicted to what I read earlier. I am still contemplating over the opposite points of view, but I’m tipped heavily toward yours. And no matter, that’s what is so great about modernized democracy and the marketplace of thoughts on-line.
I’ve been using media queries on a few projects and much prefer this method than building a seperate mobile site or something running off a javascript framework like sencha.
This is the way forward..
css 3 has some surprising quirks! Loving the new things it does though. Great blog, keep it up!
Really, you have done great job. I enjoyed while reading this one and also inspired me too much. I will use this theme on my blog as well as website. I like it very much. Thanks for upgrade my knowledge.
Los Angeles Web Design
The iPhone specific stylesheet is a great help, thanks!
My site looks better on Iphone – thanks to You
Utile article peut I mention ceci sur le mon emplacement ? Merci
white iphone 4 is so charming and chic. As the icon of latest fashion, how can you miss it!
But to really see the difference between these cameras I put together an overview containing 100% crops. It’s not fair comparing the white iPhone 4 with an 18 megapixel DSLR but it’s good to have as a reference.
Great Information and post! It is very informative and suggestible for the user of solar energy, May I think it can be beneficial in coming days…
facebook apps
nice posting and helpful info.
Love the article and I’m always finding very useful stuff on your site.
One issue I have been having with media has shown up with your demo as well. I viewed the demo on a phone and both the grey and blue box highlighted along with not fitting to the screen. I’m not sure what the issues is but it’s like a lot of phones think they have a width of over 900px but just viewed at a small size. So everything is as if you have a 900px browser just seen from far away. I hope you understand what I’m talking about. Do you know why and maybe even have a solution?
Very handy. This will solve one of the issues I’m having on my image hosting site.
First, i saw your demo and i don’t know, why should i use on a website. Your article help me to understand the possibility of this methode of css3. Thank you.
Ralph
But tell me one thin how can i test my diffrent stylsheet any testing software r u know if so plzzz tell me
Hi,
I try to use the CSS @media screen and (max-width: 600px)
and @media screen and (min-width: 600px) and (max-width: 00px)
unfortunatelly the first one (max-width: 600px) Works only in the head section of the page and not on a separate stylesheet.
I wonder where the problem is!
Recent surveys, children of depressed mothers’ negative patterns of activity occurring in different brain reveals. This is for children of mothers who take more risks in the future is going to have depression.
Can you view a website inside your website but it will automatically be smaller like the examples shown above ?
What is friendship?Mont Blanc PenWhy do we call a person our friend? When do we call someone a very good friend?
R.Q. Investigations specializes in a range of investigator services. The private investigator detective offers you a high level intelligence and analysis service molded to suit your requirements and handles investigator services with personal care and diligence.
For depuy hip replacement recall information or regarding depuy hip replacement recall lawsuit , you can contact the expert New York personal injury lawyer.
Wellensteyn-Jacken werden getragen von qualitätsbewussten Menschen, für die Stil und Outdoor-Bekleidung keinen Gegensatz darstellt. So sind die funktionalen Jacken mittlerweile Alltag auf den Straßen deutscher und internationaler Großstädte.
I love the tutorials on this blog, keep up the good work.
Hi!
Thanks for the lovely demo!
That really inspired me to keep reading.
Really great article!
Would it be to much to ask for a demo .css that one can download?
I just know there’s something I’m doing wrong cause my website I’m working on doesn’t change the when I browse it with my phone.
Thanks for all the tutorials and a Happy new year!
Good article!
How does this work when the user changes orientation? E.g. Portrait to Landscape and vice versa? Using the “max-width:480px” I have had trouble when I go from portrait to landscape on an iPhone the page looks great in portrait but then scales when I go to landscape.
This is a superbly written tutorial. Its language is simple and easy to understand.
I thoroughly enjoyed reading and understanding its content. My drive is to create a flexible Joomla template based on the information I’ve read in this tutorial.
If you have a minute, please take a look at http://www.opensourcevarsity.com it has a ton of tutorials on opensource tools and technologies.
I wonder if you would consent to doing a Guest Post, or writing a tutorial for OSV.
Regards,
Ivan Bayross
Please tell me how to solve in IE.
This specific are getting to be good yet again routines when assists you to loosen all the spinal column and likewise sleep thoroughly without the go through on the subject of kind with your once again.
I love the articles on site! Mostly quality articles, and that’s what makes me come back! :) Keep up the good work!
A very useful post as mobiles are becoming such an important source of traffic and we are currently researching how to improve the experience for our users. Thanks a lot, will be coming back!
Everything worked except for max-device-width. Can you please explain the rationale behind using max-width vs. min-width. It’s a little confusing.
Very Clear tutorial Keep up the Good work……
Thank you so much.
Very Clear tutorial Keep up the Good work……
Thank you so much.
I am very much interested to know how to use the with Phone gap..
Very nice examples, keep up the good work :)
Hi, the whole thing is going niсelу here and
οfcoursе еverу οnе is shaгіng facts, thаt’s really good, keep up writing.
Thanks Nick. I was looking for a ‘min width’ solution and yours as described worked perfectly.
Nice tutorial but why I see the 4th box which should only appear on IPhones? Either Firefox or Chrome could interpret the device-width command… Or did I use it the wrong way??? Only max and min-width works for me, could you help me why?
I am trying to hide two modules, i have made custom css and put:
/* Smartphones */
@media (max-width: 480px) {
#full_left { display: none; }
#full_right { display: none; }
}
/* Smartphones to Tablets */
@media (min-width: 481px) and (max-width: 767px) {
#full_left { display: none; }
#full_right { display: none; }
}
/* Tablets */
@media (min-width: 768px) and (max-width: 959px) {
#full_left { display: none; }
#full_right { display: none; }
But they still shows in ipad/iphone…
Any idea?