css - Responsive Flex
When you want a responsive layout using Flexbox, you rely on flex properties combined with media queries to make elements adapt to different screen sizes. I'll explain everything step by step with examples.
1. Basic Responsive Flex Layout
HTML
<div class="container">
<div class="item">Box 1</div>
<div class="item">Box 2</div>
<div class="item">Box 3</div>
</div>
CSS
.container {
display: flex;
flex-wrap: wrap; /* Allow items to wrap */
gap: 20px;
}
.item {
flex: 1 1 300px; /* Grow, shrink, and minimum width */
background-color: #4caf50;
color: white;
padding: 20px;
text-align: center;
border-radius: 8px;
}
How it works:
-
display: flex
→ enables flexbox. -
flex-wrap: wrap
→ items automatically move to a new row when there’s no space. -
flex: 1 1 300px
→-
1
= can grow equally, -
1
= can shrink if needed, -
300px
= preferred width.
-
Result:
-
On large screens → items appear side by side.
-
On smaller screens → items wrap into rows automatically.
2. Responsive Design with Media Queries
You can make the layout adapt better by combining flexbox with media queries.
CSS
.container {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.item {
flex: 1 1 300px;
padding: 20px;
background-color: #2196f3;
color: white;
text-align: center;
border-radius: 8px;
}
/* Tablet View */
@media (max-width: 768px) {
.container {
flex-direction: column; /* Stack items vertically */
}
}
Result:
-
Desktop → items in a row.
-
Tablet & Mobile → items stack vertically.
3. Using flex-basis
for Better Control
.item {
flex: 1 1 250px; /* min width of 250px */
}
-
If the screen is wide → items spread out.
-
If the screen shrinks below
250px
per item → items wrap into a new row.
4. Using gap
for Responsive Spacing
Instead of using margin
, use gap
:
.container {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
-
gap
automatically adjusts spacing between flex items, making layouts cleaner.
5. Example: Fully Responsive Cards
<div class="cards">
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>
<div class="card">Card 4</div>
</div>
.cards {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
flex: 1 1 250px;
padding: 20px;
background-color: #673ab7;
color: white;
text-align: center;
border-radius: 10px;
}
Effect:
-
4 cards in a row on large screens
-
2 cards per row on medium screens
-
1 card per row on mobile