This page looks best with JavaScript enabled

Move Item to Next Row on Resize with Flexbox

 ·   ·  β˜• 2 min read

In this tutorial, I’ll show how to make items of a flexbox to go to the next line on the window resize.

There comes a time in life when you need to create layouts where block snaps to next line when the window is too narrow. This is a best practice in responsive web design.

The Setup

Let’s get started creating a skeleton for our experiments:

1
2
3
4
5
6
<div class="flex">
<div class="item">HTML</div>
<div class="item">CSS</div>
<div class="item">JavaScript</div>
<div class="item">MongoDB</div>
</div>

As we have the skeleton, let’s start designing. We’ll add display: flex; to make that div flex or parent to flex items.

1
2
3
4
5
6
7
8
.flex {
  display: flex;
  justify-content: space-around;
}

.item {
  border: 3px solid whitesmoke;
}

justify-content: space-around; tells the browser to maintain an equal amount of space between all the content.

Let’s proceed giving our .item some width. So that when we resize the window we get the effect.

1
width: 180px;

At this stage, all items would appear on the same line. After we resize the window, it maintains the line.

The Magic

By default, flexboxes don’t allow items to be spread on multiple lines. This can be overridden flex-wrap property. We’ll add flex-wrap: wrap; property to the flex container.

1
flex-wrap: wrap;

This tells the browser to break to another line if there is no more space.

So if the viewport is 600px wide, then 600/180 i.e. only 3 flex items could fit on the first line. See this pen for the understanding.Β There are more topics in flex to talk about. But I would like to wrap up this post here.

flex-wrap: wrap
flex-wrap: wrap

Please leave a comments, hugs or bugs all welcome. Also please subscribe to the newsletter below.

Share on

Santosh Kumar
WRITTEN BY
Santosh Kumar
Santosh is a Software Developer currently working with NuNet as a Full Stack Developer.