Mobile-first media queries in CSS
31 Mobile first, and only upwards
fairStyle a card list for a narrow screen with no media query at all, then add two breakpoints that only ever add columns. Nothing in a query may undo something the base rules did.
Stuck? Three hints, smallest first
- 1. Write the small-screen layout as the base rules, outside every query.
- 2. Then use
min-widthqueries in ascending order, each one adding to the last. - 3. If a query has to reset something, the base rules were written for the wrong screen.
<ul class="cards">
<li>Abuja</li>
<li>Kano</li>
<li>Enugu</li>
<li>Ibadan</li>
</ul>
/* Base: one column. No query, because this is the default case. */
.cards {
display: grid;
grid-template-columns: 1fr;
gap: 8px;
margin: 0;
padding: 0;
list-style: none;
}
.cards li {
padding: 12px;
background: #eef1fd;
border: 1px solid #3055d8;
border-radius: 8px;
font-size: 0.85rem;
text-align: center;
}
/* Then add, in ascending order. Neither query undoes anything above. */
@media (min-width: 26em) {
.cards { grid-template-columns: repeat(2, 1fr); }
}
@media (min-width: 44em) {
.cards { grid-template-columns: repeat(4, 1fr); }
}
8 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
// Split the stylesheet into base rules and query blocks.
const base = css.replace(/@media[^{]*\{[\s\S]*?\n\}/g, '');
const queries = [...css.matchAll(/@media \(([a-z-]+): ([\d.]+)em\)/g)]
.map((m) => ({ feature: m[1], at: Number(m[2]) }));
test('the single-column layout is a base rule', /grid-template-columns:\s*1fr/.test(base), true);
test('two breakpoints', queries.length, 2);
test('both are min-width, so the styles only ever add', queries.every((q) => q.feature === 'min-width'), true);
test('and they are written in ascending order', queries.map((q) => q.at), [26, 44]);
test('no max-width query anywhere', /max-width/.test(css), false);
test('the queries change only the column count', (css.match(/@media[^{]*\{\s*\.cards \{ grid-template-columns/g) || []).length, 2);
test('nothing in a query resets a base declaration', /@media[\s\S]*(display:\s*block|list-style)/.test(css), false);
test('four cards, in a real list', countTag(html, 'li') === 4 && hasTag(html, 'ul'), true);
Output
Mobile first is not about phones, it is about which case needs no query. The narrow layout is almost always the simpler one — a single column, everything stacked — so making it the base means the queries only ever add. That fails better too: if a query never matches, or its syntax is wrong, or the stylesheet is truncated, what the reader gets is the plain stacked version rather than a half-applied grid. The last check is the honest test of whether you really did it: any reset inside a query is a sign the base rules were written for a desktop.