CSSbeginner 9 min
Line up and space out elements in a row or column with display flex.
How to put items side by side, space them evenly and centre them with flexbox.
Navigation bars, card rows and centred content are everywhere. Flexbox makes them a few lines of CSS instead of a fight.
Flexbox works on a container and its direct children (the items). Set display: flex on the container and the items line up in a row.
Key properties on the container:
flex-direction: row (default) or column.justify-content: how to distribute items along the main axis: flex-start, center, space-between, space-around.align-items: how to align items on the other axis: stretch, center, flex-start.gap: space between items.On an item, flex: 1 makes it grow to share the leftover space.
display: flex turns .row into a flex container, so the three items sit in a row.justify-content: space-between pushes the first item to the left edge, the last to the right, and spreads the middle one.align-items: center centres them vertically in the 120px height.gap: 12px keeps a minimum space between items.Change justify-content to center, then to flex-end. Then set flex-direction: column and see what happens.
display: flex on the items instead of the container.justify-content follows the main direction, align-items the cross direction. They swap when you use column.display: flex on the container lines items up.justify-content, align-items and gap position and space them.flex-direction: column switches to a vertical stack.You finished the CSS beginner section. Next: grid, responsive design and transitions.
<style>
.row {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
background: #e2e8f0;
padding: 12px;
height: 120px;
}
.item {
background: royalblue;
color: white;
padding: 16px;
border-radius: 8px;
}
</style>
<div class="row">
<div class="item">One</div>
<div class="item">Two</div>
<div class="item">Three</div>
</div>