What is a media query?
A media query applies a block of CSS only when a condition about the viewport is met (usually, its width). It's the tool that makes the design change according to the screen size.
@media (min-width: 768px) {
.gallery {
flex-direction: row; /* on screens >= 768px, in a row */
}
}
Read it literally: "from 768 px of width on, the gallery goes in a row". Below that width, the base style still applies (the column).
Typical breakpoints
A breakpoint is the width at which the design changes. There are no sacred values, but these are common:
@media (min-width: 640px) { /* large phone / portrait tablet */ }
@media (min-width: 768px) { /* tablet */ }
@media (min-width: 1024px) { /* laptop */ }
@media (min-width: 1280px) { /* wide desktop */ }
Expert tip: choose breakpoints based on where your content breaks, not on specific device models. Resize the window and, when the design starts to look bad, that's where you put the breakpoint.
Why min-width fits with mobile-first
With mobile-first we use min-width (from small to large):
- The base style (outside media queries) is the mobile one.
- Each
@media (min-width: ...)adds improvements as there is more space. - The rules accumulate from smaller to larger width, in increasing order.
The opposite approach, max-width (from large to small), is desktop-first:
you start with desktop and keep trimming. It works, but it usually ends in more
code and more exceptions. For most projects, mobile-first +
min-width is the recommended option.