Flexbox Patterns
Real-world flexbox patterns you'll use again and again - navigation bars, card layouts, media objects, and more
Common Flexbox Patterns
Real-world flexbox patterns you'll use again and again in your projects.
Navigation Bar
/* Responsive navigation */
.nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
}
.nav-menu {
display: flex;
gap: 2rem;
list-style: none;
}
/* Push items apart */
.nav-brand { margin-right: auto; }
Card Layout
Card 1
Flexible card that grows to fill space.
Card 2
All cards maintain equal height.
Card 3
Button always at the bottom.
/* Equal height cards */
.cards {
display: flex;
gap: 1rem;
}
.card {
flex: 1;
display: flex;
flex-direction: column;
}
.card p {
flex: 1; /* Push button to bottom */
}
Media Object
Media Object Pattern
Image on the left, content on the right. A classic pattern made simple with flexbox.
/* Media object pattern */
.media {
display: flex;
gap: 1rem;
align-items: flex-start;
}
.media-image {
flex: 0 0 100px; /* Fixed width */
}
.media-content {
flex: 1; /* Take remaining space */
}
Sticky Footer
/* Sticky footer pattern */
.page {
min-height: 100vh;
display: flex;
flex-direction: column;
}
.header, .footer {
flex: 0 0 auto;
}
.main {
flex: 1 0 auto;
}
Input Groups
@
/* Input group pattern */
.input-group {
display: flex;
}
.input-group input {
flex: 1;
border-radius: 0;
}
.input-addon {
display: flex;
align-items: center;
padding: 0 1rem;
background: var(--colour-surface);
}
Holy Grail Layout
/* Holy grail layout */
.layout {
display: flex;
gap: 1rem;
}
.sidebar-left,
.sidebar-right {
flex: 0 0 200px; /* Fixed width */
}
.main-content {
flex: 1; /* Flexible center */
}
/* Responsive */
@media (max-width: 768px) {
.layout { flex-direction: column; }
}
Flexbox Pro Tips
Use Gap Instead of Margins
The gap property is cleaner and doesn't require nth-child selectors to remove edge margins.
Min-Width: 0 for Truncation
Flex items have min-width: auto by default. Set to 0 to allow text truncation.
Flex: 1 1 0 vs Flex: 1
Flex: 1 is shorthand for flex: 1 1 0, which makes items grow equally from 0 basis.