How to make two columns
Short answer
A grid of two equal columns:
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
<div style="padding: 12px; background: lavender;">Left column</div>
<div style="padding: 12px; background: honeydew;">Right column</div>
</div>The fr unit is a share of the free space: 1fr 1fr splits it in half, 2fr 1fr in a two-to-one ratio.
A sidebar and content
The first column is fixed, the second takes the rest:
<div style="display: grid; grid-template-columns: 140px 1fr; gap: 16px;">
<div style="padding: 12px; background: lavender;">Menu</div>
<div style="padding: 12px; background: honeydew;">Main content</div>
</div>The same with flexbox
flex: 1 shares the width equally between the columns:
<div style="display: flex; gap: 16px;">
<div style="flex: 1; padding: 12px; background: lavender;">One</div>
<div style="flex: 1; padding: 12px; background: honeydew;">Two</div>
</div>One column on a phone
The columns are switched on only on a wide screen:
<style>
.cols { display: grid; gap: 16px; }
.cols div { padding: 12px; background: lightyellow; }
@media (min-width: 500px) { .cols { grid-template-columns: 1fr 1fr; } }
</style>
<div class="cols"><div>First</div><div>Second</div></div>Common mistake
Columns built with width: 50% and float break as soon as you add padding or a border: two halves plus padding are more than 100%, and the second column drops down. Grid and flexbox with gap handle the spacing themselves — use them.
Functions used in this recipe
- grid-template-columns — The number and widths of the columns of a grid.
- gap — The gaps between items in flexbox and grid.
- flex — A shorthand for how a flex item grows, shrinks and what size it starts from.
- @media — Applies rules only under given conditions — the window width, the system theme and others.