A media query is a condition written in CSS that switches styles on or off depending on the device or visitor settings. The most common use is changing a layout when the screen gets narrow, but media queries can also detect dark mode, a request for less animation, or whether the page is being printed.
Anatomy of a media query
A media query starts with @media, followed by one or more conditions in brackets, and then a block of normal CSS rules. For example, @media (min-width: 768px) { ... } applies the rules inside only when the viewport is at least 768 CSS pixels wide. The browser re-checks these conditions live, so rotating a tablet or resizing a window swaps styles instantly without reloading.
Conditions can be combined with and, separated by commas to mean "or", and modern browsers accept range syntax such as (width >= 768px). The width values where layouts change are usually called breakpoints.
What else you can query
prefers-color-scheme: darkfor visitors who set their device to dark mode.prefers-reduced-motion: reducefor people who have asked the operating system to limit animation, often because motion makes them unwell.hover: hoverandpointer: fineto tell mouse users from touch users.printto hide navigation and ads when someone prints a recipe or invoice.
Example: a restaurant menu page
A restaurant shows its menu in three columns on a laptop. A base style stacks dishes in one column for phones, then @media (min-width: 640px) adds two columns and @media (min-width: 1024px) adds the third. A print rule hides the header and photos so the menu fits on one sheet. Writing the phone layout first and adding larger screens on top is called mobile-first, and it is how Tailwind CSS prefixes like md: work.
How much a site owner needs this
Most templates and builders handle breakpoints for you. Knowing the idea helps when something looks right on your laptop and broken on your phone: the fix is almost always inside a media query. Container queries (@container), now supported in current browsers, solve a related problem by reacting to the size of a component's box instead of the screen.
Where media queries go wrong
- Breakpoints tied to specific devices. Choose widths where your content starts to look cramped, not the size of one iPhone model.
- Missing viewport meta tag. Phones then report a desktop width and your mobile queries never run.
- Overlapping ranges. A max-width of 768px and a min-width of 768px both match at exactly 768px.
- Ignoring reduced motion. Large parallax and auto-playing animations should be toned down for visitors who ask.
Related terms
- Responsive design: the approach media queries make possible.
- Viewport: the size most media queries measure.
- CSS grid: layouts that are often rearranged at breakpoints.
- Flexbox: another layout tool commonly paired with breakpoints.