What is Flexbox?
Flexbox is a one-dimensional layout model designed for distributing space and aligning items along a row or a column. Turning on display: flex on a container makes its direct children flex items.
A Basic Flex Container
<style>
.row {
display: flex;
gap: 10px;
}
.row div {
background: steelblue;
color: white;
padding: 16px;
flex: 1;
text-align: center;
}
</style>
<div class="row">
<div>1</div>
<div>2</div>
<div>3</div>
</div>Key Container Properties
| Property | Purpose |
|---|---|
| flex-direction | Main axis direction: row, column, row-reverse, column-reverse |
| justify-content | Alignment along the main axis |
| align-items | Alignment along the cross axis |
| flex-wrap | Whether items wrap onto multiple lines |
| gap | Space between flex items |
Centering with Flexbox
<style>
.center-box {
display: flex;
justify-content: center;
align-items: center;
height: 150px;
background: #eef4fb;
}
</style>
<div class="center-box">
<div>Perfectly centered</div>
</div>Flex Item Properties
Individual flex items can control how they grow, shrink, and their base size using the flex shorthand, which combines flex-grow, flex-shrink, and flex-basis.
flex-grow in Action
<style>
.layout {
display: flex;
gap: 10px;
}
.sidebar {
flex: 0 0 150px; /* don't grow, don't shrink, fixed 150px */
background: #764ba2;
color: white;
padding: 10px;
}
.main {
flex: 1; /* grow to fill remaining space */
background: #eef4fb;
padding: 10px;
}
</style>
<div class="layout">
<div class="sidebar">Sidebar</div>
<div class="main">Main content grows to fill space</div>
</div>justify-content Values
| Value | Effect |
|---|---|
| flex-start | Items packed at the start (default) |
| flex-end | Items packed at the end |
| center | Items centered |
| space-between | Equal space between items, none at the edges |
| space-around | Equal space around each item |
Wrapping Items
By default, flex items try to fit on a single line, shrinking if necessary. flex-wrap: wrap allows them to flow onto multiple lines instead.
Main Axis vs Cross Axis
With flex-direction: row, the main axis is horizontal and justify-content aligns along it, while align-items aligns along the vertical cross axis. Switching to flex-direction: column swaps these roles.
Best Practice
Reach for Flexbox whenever you need to align or distribute items along a single row or column — navbars, button groups, and centering content are classic use cases.