Topic 5 of 30
Flexbox
Overview
Flexbox is a one-dimensional layout system for arranging items in a row or column with powerful alignment and distribution controls. It solves classic layout problems like centering, equal height columns, and dynamic spacing.
Syntax
css
.container {
display: flex;
flex-direction: row; /* row | column | row-reverse */
justify-content: center; /* main axis: flex-start | center | space-between | space-around */
align-items: center; /* cross axis: flex-start | center | stretch | baseline */
flex-wrap: wrap; /* nowrap | wrap */
gap: 16px; /* space between items */
}
.item {
flex: 1; /* grow + shrink + basis shorthand */
flex-grow: 1; /* how much to grow */
flex-shrink: 0; /* prevent shrinking */
flex-basis: 200px; /* initial size */
align-self: flex-start; /* override container's align-items */
}Common Pitfalls
- justify-content works on the MAIN axis; align-items works on the CROSS axis. They swap when direction is column.
- flex: 1 is shorthand for flex: 1 1 0% — NOT flex: 1 1 auto. The difference matters for sizing.
- Interview tip: To center an element perfectly — parent: display:flex; justify-content:center; align-items:center.
Real-World Example
A responsive product card grid using flexbox:
example
css
.products-section {
display: flex;
flex-wrap: wrap;
gap: 24px;
justify-content: center;
padding: 40px 20px;
}
.product-card {
flex: 1 1 280px; /* grow, shrink, min-width 280px */
max-width: 320px;
background: #1a1a1a;
border-radius: 12px;
padding: 24px;
}
/* Perfect centering */
.hero-section {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
flex-direction: column;
gap: 16px;
}