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

PropertyUseValues
flex-directionMain directionrow (default), column, row-reverse, column-reverse
justify-contentSpace along the main axisflex-start, center, flex-end, space-between, space-around, space-evenly
align-itemsAlignment on the cross axisstretch (default), flex-start, center, flex-end
flex-wrapAllow items to go to the next linenowrap (default), wrap
gapSpace between items10px

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

PropertyUse
flex-growHow much of the free space this item takes
flex-shrinkHow much it can shrink
flex-basisStarting size
flexShorthand, like flex: 1
align-selfAlignment of one item
orderChange 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: flex turns children into flex items.
  • justify-content works along the main axis, align-items across it.
  • Use flex: 1 to share space and gap for spacing.
  • Next: CSS Grid.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.