Responsive Layout with Flexbox – Step by Step CSS Tutorial
Building a responsive layout is one of the most common tasks in web development. Flexbox makes it much easier than traditional float-based layouts. Let’s go step by step and see how each CSS property changes the layout visually.
Step 1: Basic boxes without Flexbox
We start with a simple container and a few boxes. Without any layout styles, all elements appear stacked vertically because block elements take full width by default.
.container {
background: #111;
}
.item {
background: crimson;
color: white;
padding: 20px;
margin: 5px;
}
This gives you a column of red boxes one under another.
Step 2: Adding display: flex
Now we activate Flexbox by setting display: flex on the container. Immediately, the boxes line up in a row instead of stacking vertically.
.container {
display: flex;
background: #111;
}
.item {
background: crimson;
color: white;
padding: 20px;
margin: 5px;
}
At this point, the layout is horizontal but not yet responsive.
Step 3: Adding flex-wrap: wrap
By default, Flexbox tries to fit all items on one line. If the screen is narrow, elements may shrink too much. We fix that by allowing them to wrap to the next line using flex-wrap: wrap.
.container {
display: flex;
flex-wrap: wrap;
background: #111;
}
Now, when the screen gets smaller, boxes wrap to the next line instead of shrinking infinitely. The layout becomes responsive.
Step 4: Adding flex-grow and flex-basis
Next, we control how much space each box takes. flex-grow: 1 tells each item to expand evenly to fill available space. flex-basis: 200px defines the initial width of each box before growing.
.item {
flex-grow: 1;
flex-basis: 200px;
background: crimson;
color: white;
padding: 20px;
margin: 5px;
}
Now every box starts at 200px wide but if there’s extra space, they expand equally. This ensures a neat and adaptive layout that looks good on any screen width.
Final Result
You’ve created a clean responsive layout using only a few lines of CSS. The combination of display: flex, flex-wrap, flex-grow, and flex-basis gives you full control over how elements behave across different screen sizes. This technique works perfectly for galleries, cards, or any grid-like section that needs to adjust fluidly.
Pro tip: Try adjusting the flex-basis value or removing flex-grow to see how the layout reacts. Flexbox gives you fine-grained control with very little code.