CSS Flexbox: The Complete Guide
CSS • Web Development • 7 min read
Flexbox solves CSS layout problems. Learn alignment, direction, wrapping, and common patterns.
CSS Flexbox: The Complete Guide
Flexbox is the most important CSS layout tool. It solves alignment, spacing, and distribution problems that were once difficult. Master Flexbox, and you'll build most layouts with ease.
What is Flexbox?
Flexbox is a CSS layout model that arranges items in a container. Items can grow, shrink, and align themselves automatically.
Basic Flexbox
.container {
display: flex;
}
.item {
flex: 1; /* Takes equal space */
}
Alignment
/* Horizontal alignment */
.container {
display: flex;
justify-content: center; /* center, space-between, space-around */
}
/* Vertical alignment */
.container {
display: flex;
align-items: center; /* center, flex-start, flex-end, stretch */
}
/* Both axes */
.container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh; /* Full viewport height */
}
Flex Direction
/* Row (default) */
.container { flex-direction: row; }
/* Column */
.container { flex-direction: column; }
/* Reverse */
.container { flex-direction: row-reverse; }
Flex Wrap
/* Items wrap to next line */
.container {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.item {
flex: 1 1 300px; /* Grow, shrink, minimum width */
}
Common Flexbox Patterns
Navigation Bar
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
}
Card Grid
.grid {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
flex: 1 1 300px;
}
Footer Sticking to Bottom
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.content { flex: 1; }
footer { /* Sticks to bottom */ }
Note: Flexbox is for one-dimensional layouts (row or column). For two-dimensional layouts (rows AND columns), use CSS Grid.