Mobile-First Media Queries in CSS

Writing responsive CSS that starts small and scales up with min-width.

When making a site responsive, it's tempting to build the desktop layout first and then add media queries to squeeze it onto a phone. That usually ends with a pile of overrides undoing styles you wrote earlier. Writing your CSS mobile first flips this around and keeps things a lot simpler.

Mobile first means your base styles are for small screens, and media queries add to them as the screen gets bigger.

Start with the Viewport Meta Tag

Before any media query will work on a phone, the page needs this tag in the <head>:

<meta name="viewport" content="width=device-width, initial-scale=1" />

Without it, mobile browsers pretend the screen is around 980px wide and shrink the whole page down, so your small-screen styles never kick in.

max-width vs min-width

A desktop-first stylesheet uses max-width to change things below a size:

.card {
display: flex;
padding: 32px;
}
@media (max-width: 768px) {
.card {
display: block; /* undo the flex */
padding: 16px; /* undo the padding */
}
}

A mobile-first stylesheet uses min-width to change things above a size:

.card {
padding: 16px;
}
@media (min-width: 768px) {
.card {
display: flex;
padding: 32px;
}
}

The second version never has to undo anything. Small screens get the simple styles, and bigger screens add the layout on top.

A Full Example

Here's a list of cards that stacks on phones, shows two columns on tablets and three on desktops:

.cards {
display: grid;
grid-gap: 16px;
}
@media (min-width: 600px) {
.cards {
grid-template-columns: 1fr 1fr;
}
}
@media (min-width: 1024px) {
.cards {
grid-template-columns: 1fr 1fr 1fr;
grid-gap: 24px;
}
}

Each media query only has the properties that change. Everything else is inherited from the styles above it.

Picking Breakpoints

Don't pick breakpoints based on specific devices. There are too many of them and they change every year. Instead, start with your browser window narrow and slowly make it wider. When the layout starts to look stretched or awkward, add a breakpoint there.

Most sites only need two or three:

  • 600px for large phones and small tablets
  • 768px or 900px for tablets
  • 1024px or 1200px for desktops

Order Matters

With min-width, the media queries should go from smallest to largest. Since later rules win when they have the same specificity, the larger screen styles need to come after the smaller ones:

.title {
font-size: 24px;
}
@media (min-width: 600px) {
.title {
font-size: 32px;
}
}
@media (min-width: 1024px) {
.title {
font-size: 40px;
}
}

On a 1200px screen both media queries match, and the last one wins with 40px.

Writing mobile first takes a little getting used to, but you'll end up with less CSS and far fewer overrides to keep track of.

Have some feedback on this post? .