How to Create Responsive Layout with Flexbox in CSS
Use
display: flex; on a container to enable flexbox layout, then apply flex-wrap: wrap; to allow items to move to new lines on smaller screens. Combine with flexible sizing like flex: 1; and media queries to create responsive layouts that adjust smoothly to different screen sizes.Syntax
To create a flexbox layout, set display: flex; on a container. Use flex-direction to arrange items in a row or column. flex-wrap controls if items wrap to the next line when space is tight. Use justify-content and align-items to align items horizontally and vertically.
css
.container {
display: flex; /* Enables flexbox layout */
flex-direction: row; /* Arrange items in a row (default) */
flex-wrap: wrap; /* Allow items to wrap to next line */
justify-content: flex-start; /* Align items horizontally */
align-items: stretch; /* Align items vertically */
}Example
This example shows a responsive flexbox layout where boxes wrap to new lines on smaller screens. Each box grows equally to fill available space.
css
html, body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
.container {
display: flex;
flex-wrap: wrap;
gap: 1rem;
padding: 1rem;
background: #f0f0f0;
}
.box {
flex: 1 1 200px; /* Grow, shrink, base width 200px */
background: #4a90e2;
color: white;
padding: 1rem;
border-radius: 0.5rem;
text-align: center;
min-width: 150px;
}
/* Responsive tweak for very small screens */
@media (max-width: 400px) {
.box {
flex-basis: 100%; /* Full width on tiny screens */
}
}Output
<div class="container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
<div class="box">Box 4</div>
</div>
Common Pitfalls
Not using flex-wrap: wrap; causes items to overflow horizontally instead of wrapping.
Setting fixed widths on flex items can break responsiveness if they don't shrink or wrap.
Forgetting to set a min-width or flex-basis can cause items to become too small or too large.
css
/* Wrong: No wrapping, items overflow */ .container { display: flex; flex-wrap: nowrap; /* default, no wrap */ } .box { width: 300px; } /* Right: Allow wrapping and flexible sizing */ .container { display: flex; flex-wrap: wrap; } .box { flex: 1 1 200px; min-width: 150px; }
Quick Reference
- display: flex; — activates flexbox layout on container
- flex-wrap: wrap; — lets items move to next line if needed
- flex: 1 1 auto; — makes items flexible in size
- justify-content — aligns items horizontally
- align-items — aligns items vertically
- Use media queries to adjust
flex-basisorflex-directionfor different screen sizes
Key Takeaways
Set
display: flex; and flex-wrap: wrap; on the container for responsive layouts.Use flexible sizing with
flex: 1 1 base-size; to let items grow and shrink smoothly.Add
min-width to prevent items from becoming too small on narrow screens.Use media queries to adjust flex properties for different device widths.
Avoid fixed widths without flexibility to keep layouts responsive and neat.