You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Flexbox — short for Flexible Box Layout — is a CSS layout model designed to distribute space and align items inside a container, even when their sizes are unknown or dynamic. It is the most widely used layout tool in modern CSS.
To enable flexbox, set display: flex on a parent element. That parent becomes the flex container and its direct children become flex items:
.container {
display: flex;
}
<div class="container">
<div class="item">One</div>
<div class="item">Two</div>
<div class="item">Three</div>
</div>
By default the items line up in a row, left to right.
The flex-direction property sets the main axis — the direction items flow:
.container {
display: flex;
flex-direction: row; /* default: left to right */
flex-direction: row-reverse; /* right to left */
flex-direction: column; /* top to bottom */
flex-direction: column-reverse; /* bottom to top */
}
Two properties control alignment:
.container {
display: flex;
justify-content: flex-start; /* default */
justify-content: flex-end;
justify-content: center;
justify-content: space-between; /* equal gaps between items */
justify-content: space-around;
justify-content: space-evenly;
align-items: stretch; /* default — items fill cross-axis height */
align-items: flex-start;
align-items: flex-end;
align-items: center; /* vertically centre items */
align-items: baseline;
}
Centering an element — historically one of CSS's hardest problems — is now trivial:
.centered {
display: flex;
justify-content: center;
align-items: center;
}
Individual items can control their own behaviour:
.item {
flex-grow: 1; /* take up available space */
flex-shrink: 1; /* shrink if needed */
flex-basis: 200px; /* starting size before growing/shrinking */
/* Shorthand */
flex: 1; /* grow: 1, shrink: 1, basis: 0 */
flex: 0 0 200px; /* fixed 200px, no grow, no shrink */
}
Setting flex: 1 on all items makes them share available space equally.
By default flex items stay in a single line and shrink to fit. Enable wrap to let items move to the next line:
.container {
display: flex;
flex-wrap: wrap;
gap: 16px; /* gap between rows and columns */
}
.item {
flex: 0 0 calc(33.333% - 16px); /* three-column grid */
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.