CSS flexbox layout
What is Flexbox?
Flexbox (Flexible Box Layout) is a CSS layout model designed for one-dimensional layouts — arranging items in a row or a column with flexible sizing and alignment.
Enabling Flexbox
css
.container {
display: flex; /* or inline-flex */
}All direct children of a flex container become flex items.
Main Axis and Cross Axis
Flexbox works along two axes:
- Main axis — defined by
flex-direction(default: horizontal, left to right) - Cross axis — perpendicular to the main axis
css
.container {
display: flex;
flex-direction: row; /* Main axis: horizontal (default) */
/* flex-direction: column; Main axis: vertical */
}Container Properties
| Property | Description |
|---|---|
flex-direction | Direction of items: row, row-reverse, column, column-reverse |
flex-wrap | Whether items wrap: nowrap, wrap, wrap-reverse |
justify-content | Alignment along main axis: flex-start, center, space-between, space-around, space-evenly |
align-items | Alignment along cross axis: stretch, flex-start, center, flex-end, baseline |
align-content | Alignment of wrapped lines: same values as justify-content |
gap | Spacing between flex items |
Example: Centering Content
css
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}Item Properties
| Property | Description |
|---|---|
flex-grow | How much an item should grow relative to others (default: 0) |
flex-shrink | How much an item should shrink relative to others (default: 1) |
flex-basis | Initial size before growing/shrinking (default: auto) |
flex | Shorthand for flex-grow flex-shrink flex-basis |
align-self | Override align-items for a single item |
order | Change visual order without changing HTML |
Example: Flexible Items
css
.sidebar { flex: 0 0 250px; } /* Fixed 250px, no grow, no shrink */
.main { flex: 1; } /* Takes all remaining space */
.aside { flex: 0 0 200px; } /* Fixed 200px */Common Flexbox Patterns
Navigation Bar
css
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 20px;
}Equal-height Cards
css
.cards {
display: flex;
gap: 16px;
flex-wrap: wrap;
}
.card {
flex: 1 1 300px; /* Grow, shrink, min 300px */
}Sticky Footer
css
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main { flex: 1; }Important:
Flexbox is best for one-dimensional layouts (a single row or column). For two-dimensional layouts (rows AND columns simultaneously), use CSS Grid. In practice, flex and grid are often combined.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.