Emmanuel Akinfulubi

HTML and CSSPractical I

Two columns that stack on mobile in CSS

14 Two columns that become one

fair

Lay out a sidebar and a main area side by side on a wide screen, stacking to one column when narrow. Then do it again with no media query at all.

Stuck? Three hints, smallest first
  1. 1. The media-query version is grid-template-columns: 200px 1fr inside a min-width query.
  2. 2. The query-free version uses flex-wrap: wrap plus a flex-basis that forces a wrap when there is no room.
  3. 3. flex: 1 1 20rem means "grow, shrink, but do not go under 20rem before wrapping".

index.html

<div class="layout">
  <aside>Sidebar</aside>
  <main>Main content area</main>
</div>

<div class="fluid">
  <div>Also sidebar</div>
  <div>Also main</div>
</div>

style.css

/* Version one: explicit, with a breakpoint. */
.layout {
  display: grid;
  gap: 12px;
  margin-bottom: 16px;
}

@media (min-width: 480px) {
  .layout { grid-template-columns: 200px 1fr; }
}

/* Version two: no media query. The basis decides when it wraps. */
.fluid {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.fluid > * {
  flex: 1 1 12rem;   /* grow, shrink, wrap below 12rem */
}

.layout aside, .layout main, .fluid > * {
  padding: 12px;
  background: #f2f3f5;
  border-radius: 6px;
}
Rendered result. Shown, not machine-checked: there is no browser in the build.
7 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.

Checks for exercise 14

test('the grid version has a breakpoint', /@media\s*\(min-width/.test(css), true);
test('and two columns inside it', /grid-template-columns\s*:\s*200px\s+1fr/.test(css), true);
test('mobile first: one column is the default', /\.layout\s*\{[^}]*display\s*:\s*grid/.test(css), true);
test('the fluid version wraps', declares(css, 'flex-wrap', 'wrap'), true);
test('and uses a flex basis to decide when', /flex\s*:\s*1\s+1\s+12rem/.test(css), true);
test('semantic aside and main', hasTag(html, 'aside') && hasTag(html, 'main'), true);
test('both layouts are present', countTag(html, 'div') >= 4, true);

Output


      

Two approaches, and the second is worth reaching for more often than people do. flex: 1 1 12rem tells each child "you may grow and shrink, but below 12rem wrap instead" — so the layout responds to the space it actually has rather than to the viewport width, which is what you usually meant. Note the grid version is mobile-first: one column is the default and the query adds the second, which fails better than the reverse.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.