Introduction to Media Queries

Learn the @media syntax to apply different CSS rules at different screen widths.

Step 1 of 5

What are media queries?

Relative units alone can't solve every responsive problem. Sometimes you need to make a dramatic layout change at a certain screen size — switch from a sidebar layout to a stacked layout, hide a navigation menu and show a hamburger icon, or change from a 3-column grid to a single column. Media queries let you write CSS rules that only apply when certain conditions are met — most commonly, when the browser window is a certain width. Think of them as 'if statements' for CSS: 'If the screen is at least 768px wide, use this layout. Otherwise, use that layout.'

When you visit Instagram on your phone, you see a single-column feed. On a desktop, you see the feed plus a sidebar with suggestions. Instagram doesn't serve a different website — it uses media queries to show different layouts based on the screen width. Every major website uses media queries: Google rearranges its search results page, YouTube switches from a grid to a stacked layout, and Amazon reorganizes its product pages.

Think of it this way: Media queries are like a thermostat. A thermostat says 'if the temperature drops below 68 degrees, turn on the heat.' A media query says 'if the screen width drops below 768 pixels, stack these columns vertically.' Both are conditional rules that trigger different behavior based on a measured value.
Web Standard
Media queries are part of the CSS3 specification (Media Queries Level 4). They can test for many conditions beyond width: screen orientation (portrait vs landscape), color scheme preference (light vs dark mode), reduced motion preference, pointer type (mouse vs touch), and more. Width-based queries are the most common for responsive design.
CSSREAD ONLY
PREVIEW