CSS Flexbox Crash Course
Real-World Flexbox Layouts
2 min read
Last updated 45 minutes ago
Let's combine everything into layouts you will actually use.
1. Centered login card
html
<div class="page">
<div class="card">
<h1>Sign in</h1>
<!-- form fields -->
</div>
</div>
css
.page {
display: flex;
min-height: 100vh;
justify-content: center;
align-items: center;
}
.card {
width: 100%;
max-width: 24rem;
padding: 2rem;
border-radius: 1rem;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}
The card is perfectly centered both ways — this alone used to require dozens of lines.
2. Responsive card grid
html
<div class="grid">
<article class="card">Card 1</article>
<article class="card">Card 2</article>
<article class="card">Card 3</article>
</div>
css
.grid {
display: flex;
flex-wrap: wrap;
gap: 1.5rem;
}
.card {
flex: 1 1 250px; /* grow, shrink, and wrap below 250px */
}
✓
wrap behavior
With flex-wrap: wrap, items drop to the next line when they no longer fit. flex: 1 1 250px makes a responsive grid with zero media queries.
3. Sticky footer layout
html
<body>
<main>Content</main>
<footer>Footer</footer>
</body>
css
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
flex: 1; /* pushes the footer to the bottom */
}
Summary
display: flexon the parent, sizing on the childrenjustify-contentfor main axis,align-itemsfor cross axisflex: 1for equal growth,flex: 0 0 <size>for fixed sizegapfor spacing,flex-wrapfor responsiveness
Practice by rebuilding the UI of your favorite website with flexbox — it's the fastest way to make it stick.
Advertisement