Error404 Error404 - 6 months ago 26
CSS Question

Flex items create space between them when they wrap

I am trying to add some

flex divs
inside a container that has
display: flex;
and I got it for big screens.

The problem is that when I make the screen smaller it seems that it creates a space between the elements that I have not set (or at least I do not think so).

This is my HTML code:

<div id="container">
<div id="left" class="block">Left</div>
<div id="center" class="block">
<div class="flexContainer">
<div class="flexDiv"></div>
</div>
<div class="flexContainer">
<div class="flexDiv"></div>
</div>
</div>
<div id="right" class="block">Right</div>
</div>


And this is my CSS code:

html, body{
width: 100%;
height: 100%;
}

#container{
display: flex;
height: 100%;
background-color: blue;
}

.block{
flex: 1;
}

#left{
background-color: green;
}

#center{
display: flex;
flex: 1;
flex-wrap: wrap;
}

#right{
background-color: orange;
}

.flexContainer{
flex: 1;
width: 50%;
min-width: 100px;
max-width: 50%;
height: 150px;
background-color: red;
padding: 10px;
}

.flexDiv{
width: 100%;
height: 100%;
background-color: yellow;
}


I have created a working JSFiddle that represents my problem.

As you can see, there is a blue space between the first and the second divs when you make the screen smaller.

How can I fix it?

Thanks in advance!

Answer

When you create a flex container, an initial setting is align-content: stretch.

This causes multiple lines of flex items to distribute themselves across the full length of the container. Hence, when flex items wrap they may separate.

Override this setting with align-content: flex-start.

#center {
    display: flex;
    flex: 1;
    flex-wrap: wrap;  
    align-content: flex-start; /* new */
}

Revised Demo

Reference:

Comments