CSS Flexbox
Flexbox is a layout system to arrange items in a row or a column, and to align and space them easily. Make an element a flex container with display: flex, and its children become flex items.
.container { display: flex; }
Three items in a row
1
2
3
Container properties
| Property | Use | Values |
|---|---|---|
flex-direction | Main direction | row (default), column, row-reverse, column-reverse |
justify-content | Space along the main axis | flex-start, center, flex-end, space-between, space-around, space-evenly |
align-items | Alignment on the cross axis | stretch (default), flex-start, center, flex-end |
flex-wrap | Allow items to go to the next line | nowrap (default), wrap |
gap | Space between items | 10px |
Centre something perfectly
.center {
display: flex;
justify-content: center; /* horizontal */
align-items: center; /* vertical */
height: 150px;
}
Output in the browser
Centred
Space between
.nav { display: flex; justify-content: space-between; align-items: center; }
Output in the browser
LogoHome About Contact
Item properties
| Property | Use |
|---|---|
flex-grow | How much of the free space this item takes |
flex-shrink | How much it can shrink |
flex-basis | Starting size |
flex | Shorthand, like flex: 1 |
align-self | Alignment of one item |
order | Change the visual order |
.sidebar { flex: 1; }
.content { flex: 3; }
The second item takes three times more space
flex: 1
flex: 3
Wrap and gap
.cards { display: flex; flex-wrap: wrap; gap: 16px; }
.card { flex: 1 1 200px; }
Note:
Flexbox arranges items in one direction (row or column). For layouts in rows and columns together, use CSS Grid.
Summary
display: flexturns children into flex items.justify-contentworks along the main axis,align-itemsacross it.- Use
flex: 1to share space andgapfor spacing. - Next: CSS Grid.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |