Flexbox Alignment
Using justify-content and align-items to position flex items along and across the main axis.
2 phút đọc
Once a container is display: flex, two properties handle almost every alignment question you'll have: justify-content for the main axis, and align-items for the cross axis.
The two axes
In a row container, the main axis runs horizontally and the cross axis runs vertically. In a column container, it's reversed. Every alignment property targets one axis or the other — mixing them up is the most common source of "why won't this center" confusion.
justify-content: the main axis
.toolbar {
display: flex;
justify-content: space-between;
}<div class="toolbar">
<button>Cancel</button>
<button>Save</button>
</div>justify-content distributes items along the main axis. Common values:
flex-start(default) — items packed at the start.center— items packed together in the middle.space-between— first and last items touch the edges, remaining space is distributed evenly between items.space-around— equal space on both sides of every item (so edge gaps are half of between-item gaps).
space-between is the classic choice for a toolbar or header with a logo on one side and navigation on the other.
align-items: the cross axis
.card {
display: flex;
align-items: center;
gap: 12px;
}<div class="card">
<img src="/avatar.jpg" alt="" width="40" height="40" />
<span>Jordan Lee</span>
</div>align-items positions items along the cross axis — in a row container, that means vertically. align-items: center is the single most common fix for "why is this icon not vertically centered next to this text," a layout problem that used to require awkward padding hacks before Flexbox existed.
Centering perfectly, both axes at once
.hero {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}This combination — justify-content: center plus align-items: center — is the standard, reliable way to center anything both horizontally and vertically, replacing older tricks involving absolute positioning and negative margins.
Aligning one item differently
.actions {
display: flex;
align-items: center;
}
.actions .spacer {
margin-left: auto;
}align-self overrides align-items for a single item. A simpler and very common trick is margin-left: auto on one flex item — it consumes all remaining space on its left, pushing everything after it to the far edge, which is a quick way to split a toolbar into a left group and a right group without space-between.