how can I remove the gap between the lines of flex blocks?
I have a certain number of red blocks, which may vary. When the number of blocks is small, the distance between the lines is large; when there is a large number, there is none. How to remove a gap with a small quantity.
.container {
width: 100%;
display: flex;
border: solid 3px black;
flex-wrap: wrap;
height: 500px;
overflow-y: scroll;
}
.container-red-box {
width: 25%;
}
.red-box {
margin: 2px;
height: 100px;
background: red;
border: solid 3px black;
}
.container-boxs {
width: 100%;
display: flex;
flex-wrap: wrap;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="container-boxs">
<div class="container-red-box">
<div class="red-box"></div>
</div>
<div class="container-red-box">
<div class="red-box"></div>
</div>
<div class="container-red-box">
<div class="red-box"></div>
</div>
<div class="container-red-box">
<div class="red-box"></div>
</div>
<div class="container-red-box">
<div class="red-box"></div>
</div>
<div class="container-red-box">
<div class="red-box"></div>
</div>
<div class="container-red-box">
<div class="red-box"></div>
</div>
<div class="container-red-box">
<div class="red-box"></div>
</div>
</div>
</div>
</body>
</html>
10 blocks:
40 blocks:
2
Answers
It is doing that because it is trying to evenly fill the container with the row wraps. If you change the
height: 500px;
on.container
tomax-height: 500px;
, it will get rid of the gapsConsider adding
align-items: flex-start
to the.container
. By default in the flex layout,align-items
is behaving asstretch
, which will make its children try to occupy the entire cross-axis. By setting it toflex-start
(orstart
), it will make them occupy only the necessary space.