Responsive Design and Media Queries by kirupa (https://www.kirupa.com/me/index.htm) | filed under HTML and CSS (https://www.kirupa.com/html5/learn_html_css.htm) TL;DR: One page can adapt to every screen. The viewport meta tag makes phones lay pages out at their real width, flexible sizes like max-width and clamp() bend with the screen, and media queries like @media (width >= 600px) add layout changes at a few breakpoints, starting from the phone layout and building up from there. - Without the viewport meta tag, phones lay a page out about 980px wide and then shrink it, so the text ends up tiny. - Mobile-first CSS puts the phone layout outside any media query, and min-width or width >= queries add to it as screens get wider. - Breakpoints work best where our content starts to look stretched or cramped, and most pages only need two or three of them. - prefers-color-scheme, prefers-reduced-motion, hover, and pointer let a page respond to the person and their device as well as the screen size. Somebody visits our page on a phone while standing in line for coffee. Somebody else visits the same page on a giant monitor at work. A third person has their browser window squished into half of a laptop screen next to a spreadsheet. They all get the same HTML, and they all expect the page to look like it was made for their screen. We could build a separate site for every screen size, but there are a bazillion screen sizes, and that sounds exhausting. In this article, we'll learn how to build one page that adapts to whatever space it's given, starting from a phone and working our way up, and we'll see how our CSS can also respond to things like dark mode and touch screens. Onwards! What Is Responsive Design? Here's the plan for our one page. We start with a layout made of flexible pieces that stretch and shrink with the screen. Then, at a few widths where those pieces start to look cramped or stretched, we change the layout. Maybe the cards go from one column to two, or a sidebar shows up. Here's one page at three widths, from a phone to a desktop monitor: [Image: The same page at 360px, 768px, and 1280px wide. At 360px, the cards stack in a single column. At 768px, the cards sit in two columns. At 1280px, a sidebar appears next to three columns of cards.] (https://www.kirupa.com/html5/images/rs_layouts.png) At 360px, the cards stack in a single column. At 768px, there's room for two columns. At 1280px, a sidebar appears next to three columns of cards. It's the same HTML in all three, and only the CSS changes how it's arranged. Building pages this way is called responsive web design, a name Ethan Marcotte gave it in a 2010 article on A List Apart (https://alistapart.com/article/responsive-web-design/). Making it work takes three things: the viewport meta tag, a flexible foundation, and media queries. Let's go through them in that order. Why Do We Need the Viewport Meta Tag? When phones first got real web browsers, almost every site was built for desktop screens. To make those sites usable, phone browsers pretended to be about 980px wide, laid the page out at that width, and then shrank the whole thing down to fit the screen. That trick still happens today on any page that doesn't tell the phone otherwise: [Image: Two phones showing the same page. Without the viewport meta tag, the phone lays the page out as if it were 980px wide and shrinks the whole thing down, so the text is tiny. With the tag, the page is laid out at the phone's own width, so the text is a readable size and the content stacks into one column.] (https://www.kirupa.com/html5/images/rs_viewport.png) On the left, the phone laid our page out at 980px, so our carefully planned phone layout never kicks in, and the text is too tiny to read without zooming. On the right, the page was laid out at the phone's own width. The fix is one line in the head of every page: The width=device-width part tells the browser to lay the page out at the screen's real width, and initial-scale=1 tells it not to zoom in or out when the page loads. You'll sometimes see user-scalable=no or maximum-scale=1 added to that line. Please don't add those. They stop people from zooming in, and people with low vision rely on zooming to read. If you're curious about the different widths a browser keeps track of, Viewport, Device, and Document Size (https://www.kirupa.com/html5/viewport_device_document_size.htm) goes into more detail. How Do We Build a Flexible Foundation? Before we write a single media query, we want a layout that already bends a little. A page made of fixed pixel widths breaks the moment the screen is narrower than those widths, while a page made of flexible sizes keeps working across a wide range of screens on its own. Here are a few habits that get us most of the way there: .page { max-width: 1100px; margin-inline: auto; padding-inline: 16px; } img, video { max-width: 100%; height: auto; } h1 { font-size: clamp(1.75rem, 1rem + 3vw, 3rem); } The .page rule lets our content fill narrow screens while never growing wider than 1100px, and it keeps it centered with a little breathing room on the sides. The image rule keeps pictures from poking out of their container, and height: auto keeps them from getting squished. The clamp() function gives our heading a size that grows with the screen width (vw is 1% of the viewport's width), but never shrinks below 1.75rem or grows past 3rem. Layout tools help too. A flex container with flex-wrap: wrap, or a grid with repeat(auto-fill, minmax(150px, 1fr)), already adjusts how many items fit in a row. We cover both in Flexbox Fundamentals (https://www.kirupa.com/html5/flexbox_fundamentals.htm) and CSS Grid Fundamentals (https://www.kirupa.com/html5/css_grid_fundamentals.htm). What Is a Media Query? A flexible foundation only goes so far. At some point, we want to change the layout itself, like switching from one column of cards to two. To do that, our CSS needs to ask a question about the screen, like "is it at least 600px wide?", and only use some rules when the answer is yes. That question is called a media query, and we write it with the @media rule: @media (width >= 600px) { .cards { grid-template-columns: 1fr 1fr; } } Everything inside the curly braces only applies when the viewport is at least 600px wide. When someone narrows their browser below 600px, those rules switch off right away, with no reload needed. The part in parentheses is called a media feature, and width is the one we'll use the most. The >= comparison is the newer range syntax. It has worked in every major browser since Safari 16.4 shipped in March 2023 (Chrome 104 and Firefox 63 had it earlier). You'll still see the older way of writing the same thing in plenty of code, and it works everywhere too: /* The same query, written the older way */ @media (min-width: 600px) { .cards { grid-template-columns: 1fr 1fr; } } /* Between 600px and 999px */ @media (600px <= width < 1000px) { .sidebar { display: none; } } We can combine features with and, list alternatives with a comma, and flip a query with not. We can also start a query with a media type, like @media print, to style the page differently when someone prints it. Our Creating Printer Friendly Pages (https://www.kirupa.com/html5/creating_printer_friendly_pages.htm) tutorial puts that one to work. What Does Mobile-First Mean? There are two ways to organize our media queries. We can write the desktop layout first and then use max-width queries to undo parts of it for smaller screens. Or we can write the phone layout first, as plain CSS outside of any media query, and then use min-width (or width >=) queries to add to it as the screen gets wider. The second way is called mobile-first, and it's the one most people recommend. Here's how its layers stack up: [Image: A ruler from 0 to 1200px with breakpoints at 600px and 1000px. The base styles apply at every width. The rules inside (width >= 600px) add on top starting at 600px, and the rules inside (width >= 1000px) add on top of both starting at 1000px.] (https://www.kirupa.com/html5/images/rs_layers.png) The base styles apply at every width. Starting at 600px, the rules in the first media query add on top of them. Starting at 1000px, the rules in the second media query add on top of both. A screen that's 1200px wide gets all three layers, and a phone only gets the first. Here's the layout part of the CSS that goes with it, from the little Waffle Hub page we'll play with in a moment: /* Base styles: every width gets these */ .page { display: grid; gap: 12px; } .cards { display: grid; gap: 12px; } aside { display: none; } /* Wider than a phone: the cards pair up */ @media (width >= 600px) { .cards { grid-template-columns: 1fr 1fr; } } /* Wide screens: a sidebar and three columns of cards */ @media (width >= 1000px) { .page { grid-template-columns: 200px 1fr; } aside { display: block; } .cards { grid-template-columns: repeat(3, 1fr); } } Mobile-first works well for a few reasons. The phone layout is usually the simplest one, a single column, so the base styles stay short, and the media queries only add things. Adding is a lot easier to reason about than undoing. It also keeps the order of our rules in step with how the cascade works. When two rules set the same property, the later one wins, so the wider-screen rules further down the file override the base styles above them. How Do We Pick Breakpoints? The widths where our layout changes are called breakpoints. It's tempting to pick them from a list of popular devices, but there are thousands of screen sizes and new ones show up every year. A more reliable approach is to let our content decide. Start with the browser window as narrow as a phone, then slowly make it wider. When the layout starts to look stretched, like lines of text so long they're hard to read or cards that are awkwardly wide, that's a good spot for a breakpoint. Most pages only need two or three breakpoints. The numbers don't have to be round, either. If our cards look best in two columns starting at 560px, then 560px is a perfectly good breakpoint. Let's Play With a Responsive Page Here's the Waffle Hub page from the code above, inside a frame whose width you control. The page has breakpoints at 600px and 1000px, and the code below it lights up the media queries that are active: Live demo: A Viewport width slider that resizes a small mobile-first page called Waffle Hub from 320px to 1200px wide, with chips and code that show which of its media queries, at 600px and 1000px, are active (https://www.kirupa.com/html5/examples/responsive_playground.htm) Try it: 1. Drag the Viewport width slider slowly to the right 2. Watch the cards pair up at 600px 3. Keep going until the sidebar appears at 1000px Notice that the header changes at 600px too, with the links moving up next to the title. Once the page gets wider than the frame, it's scaled down to fit so you can still see the whole thing, the same way the phone in our earlier figure shrank the 980px page. What Else Can Media Queries Check? Width gets most of the attention, but media queries can ask about a lot more than the size of the screen. Several of the most useful ones start with prefers-, and they tell us about settings people have chosen on their device: Media feature | What it tells us | Example prefers-color-scheme | Whether someone has picked a light or dark theme for their device | (prefers-color-scheme: dark) prefers-reduced-motion | Whether someone has asked for less animation | (prefers-reduced-motion: reduce) prefers-contrast | Whether someone wants more (or less) contrast between colors | (prefers-contrast: more) hover and pointer | Whether the main way of pointing can hover, and whether it's precise like a mouse or coarse like a finger | (hover: hover) and (pointer: fine) orientation | Whether the viewport is taller than it is wide | (orientation: portrait) Dark mode is a great example of how these fit together with the rest of our CSS. If we keep our colors in custom properties, a single media query can swap all of them at once: :root { --page: #ffffff; --text: #1e2933; } @media (prefers-color-scheme: dark) { :root { --page: #1e2933; --text: #eaf7ff; } } body { background-color: var(--page); color: var(--text); } The hover and pointer features are handy for things that only make sense with a mouse. A menu that opens on hover is fine on a laptop, but a phone has no way to hover, so we can save that behavior for devices that can actually do it and make sure tapping works everywhere. For motion, Respecting Reduced Motion (https://www.kirupa.com/animations/respecting_reduced_motion.htm) covers what to do when someone asks for less of it. Every media query we write in CSS can also be checked in JavaScript. The matchMedia method takes the same query, tells us whether it matches right now, and fires a change event when the answer flips: const wide = window.matchMedia("(width >= 1000px)"); console.log(wide.matches); wide.addEventListener("change", () => { console.log("Wide layout:", wide.matches); }); How Do We Test a Responsive Page? The quickest check is to make the browser window narrower and wider and watch what happens. For a closer look, every major browser has a responsive mode in its developer tools. In Chrome and Edge, it's the device toolbar, in Firefox it's Responsive Design Mode, and Safari has one under the Develop menu. They let us type in an exact width, pretend to be a touch screen, and even pretend dark mode or reduced motion is turned on. Developer tools can't tell us everything, though. They don't know how a page feels when it's held in one hand, or how small a tap target is under a real thumb. So before calling a page done, it's worth opening it on an actual phone. What About Components That Live in Different Places? Media queries ask about the whole screen. Most of the time, that's exactly what we want, since the screen decides how much room our page has. Things get trickier with components that show up in more than one place. A product card in a wide main column and the same card in a narrow sidebar get exactly the same answer from a media query, because they're on the same screen. For that, CSS has a newer tool that asks about the space around a component instead, and we cover it in Container Queries (https://www.kirupa.com/html5/container_queries.htm). Frequently Asked Questions What Does the Viewport Meta Tag Do? It tells phones to lay the page out at the screen's real width instead of pretending to be about 980px wide. Without it, the phone shrinks a desktop-sized layout to fit, so the text is tiny and our phone layout never kicks in. What Is Mobile-First CSS? It means writing the phone layout as the base styles, outside of any media query, and then using min-width or width >= media queries to add to it as screens get wider. The base styles stay simple, and each media query only adds things, which is easier to follow than undoing a desktop layout. What Breakpoints Should I Use? Pick them from your content instead of a list of devices. Start with a narrow window, slowly widen it, and add a breakpoint where the layout starts to look stretched or cramped. Most pages only need two or three, and the numbers don't need to be round. What Is the Difference Between min-width and width >= in a Media Query? They mean the same thing. (min-width: 600px) is the older way of writing it, and (width >= 600px) is the newer range syntax, which has worked in every major browser since Safari 16.4 shipped in March 2023. How Do I Detect Dark Mode in CSS? Use the prefers-color-scheme media feature. Rules inside @media (prefers-color-scheme: dark) only apply when someone has picked a dark theme for their device. Keeping colors in custom properties lets one media query swap all of them at once. Conclusion Responsive design comes down to a few habits. We add the viewport meta tag so phones lay our page out at their real width. We build with flexible sizes, like max-width, the fr unit, and clamp(), so the page already adapts a little on its own. Then we write the phone layout first and use media queries at a few breakpoints, picked by our content, to add to it as the screen grows. The prefers- features are where things get personal. They let our page respond to the person using it as well as their screen, whether that's a dark theme, less motion, or more contrast. Those are some of the easiest wins in CSS, and people notice. Before you go, here are a few things you can do: 1. Test your knowledge by taking the quiz below. 2. Check out some related content: - Container Queries (https://www.kirupa.com/html5/container_queries.htm). Let a component change its layout based on the space it sits in. - Respecting Reduced Motion (https://www.kirupa.com/animations/respecting_reduced_motion.htm). Tone down motion for people who ask their device for less of it. - Viewport, Device, and Document Size (https://www.kirupa.com/html5/viewport_device_document_size.htm). Measure the viewport, device, and document size with JavaScript. 3. Stuck on something, or curious about a detail we skipped? Ask on the forums (https://forum.kirupa.com/), and we'll help you out. [Mastery Quiz] Test your knowledge! Take the Reviewing Responsive Layouts Quiz: https://www.kirupa.com/quizzes/responsive_design_media_queries.htm Practice with 4 multiple-choice questions and an explanation after every answer. [/Mastery Quiz]