CSS Tutorial · CSS Layout · Lesson 12 of 19
CSS Flexbox
One-dimensional layouts: direction, alignment, wrapping, gap and flexible sizes.
Flex containers
display: flex lays out the children (flex items) in a row or column:
| Property (container) | Controls |
|---|---|
flex-direction |
row (default) or column |
justify-content |
alignment on the main axis: flex-start, center, space-between… |
align-items |
alignment on the cross axis: stretch, center, flex-start… |
flex-wrap |
allow items to wrap onto new lines |
gap |
space between items |
<style>
body { font: 14px system-ui, sans-serif; }
.row { display: flex; gap: 8px; padding: 8px; background: #f1f5f9; margin-bottom: 10px; border-radius: 8px; }
.row div { background: #2563eb; color: white; padding: 8px 12px; border-radius: 6px; }
.between { justify-content: space-between; }
.center { justify-content: center; align-items: center; height: 80px; }
.wrap { flex-wrap: wrap; width: 220px; }
</style>
<div class="row"><div>1</div><div>2</div><div>3</div></div>
<div class="row between"><div>Logo</div><div>Menu</div></div>
<div class="row center"><div>Centred</div></div>
<div class="row wrap"><div>One</div><div>Two</div><div>Three</div><div>Four</div><div>Five</div></div>
Flexible items
flex: 1 makes an item grow to fill free space. flex: 0 0 200px fixes it at 200px.
<style>
.layout { display: flex; gap: 10px; font: 14px system-ui; height: 120px; }
.sidebar { flex: 0 0 120px; background: #e2e8f0; padding: 8px; }
.content { flex: 1; background: #dbeafe; padding: 8px; }
.toolbar { display: flex; gap: 6px; margin-top: 10px; }
.toolbar input { flex: 1; }
</style>
<div class="layout">
<aside class="sidebar">Sidebar (120px)</aside>
<main class="content">Content grows to fill the rest</main>
</div>
<div class="toolbar"><input placeholder="Search grows"><button>Go</button></div>
Perfect centring is two lines: display: flex; place-items: center on grid, or justify-content: center; align-items: center on flex.
Test yourself
Which property distributes flex items along the main axis?
align-itemsjustify-contentflex-wrapalign-content
Show answer
Answer: justify-content