Flexbox Intro
On this page
What Is Flexbox?
Flexbox (Flexible Box Layout) is a CSS layout model designed to align and distribute space between items in a container. It is especially useful for:
- centering content
- building navbars
- creating responsive rows/columns
- aligning items with different sizes
Flex Container and Flex Items
To use Flexbox, set display: flex on a container. The direct children become flex items.
.container {
display: flex;
}
<div class="container"> <div class="item">A</div> <div class="item">B</div> <div class="item">C</div> </div>
Main Axis vs Cross Axis
Flexbox layouts are based on two axes:
- Main axis – the primary direction (row or column)
- Cross axis – the direction perpendicular to the main axis
By default:
flex-direction: row(main axis is left-to-right)- cross axis is top-to-bottom
.container {
display: flex;
flex-direction: row;
}
Common Flexbox Controls
Some of the most used Flexbox properties:
flex-direction– row/column directionjustify-content– alignment on the main axisalign-items– alignment on the cross axisgap– spacing between itemsflex-wrap– allow items to wrap
.container {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
}
Example: Perfect Centering
Flexbox makes centering simple:
.center {
display: flex;
justify-content: center;
align-items: center;
height: 240px;
}
Example: Responsive Wrapping Row
Use flex-wrap to let items wrap to a new line when there is not enough space.
.row {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.card {
flex: 1 1 240px; /* grow, shrink, basis */
}
Summary
- Flexbox is great for alignment and distributing space.
- Apply
display: flexto a container; children become flex items. - Understand main axis vs cross axis to use
justify-contentandalign-itemscorrectly. - Use
flex-wrapandflexto build responsive rows.