0

I've a div container (the grey one), with contains some children with a flex display. The container can scroll vertically.

The height of the gray container should be the same as the window.

.container {
  width: 500px;
  height: 100vh;
  background-color: lightgrey;
  padding: 10px;
  overflow: auto;
  display: flex;
  flex-wrap: wrap;
}

.item {
  width: 200px;
  height: 200px;
  background-color: gold;
  border: 1px solid orange;
}
<div class="container">
  <div class="item" ></div>
  <div class="item" ></div>
  <div class="item" ></div>
  <div class="item" ></div>
  <div class="item" ></div>
  <div class="item" ></div>
  <div class="item" ></div>
</div>

If you run the snippet, you can see the result: each item is near another item and the container scrolls.

The problem is that if I remove some items (their number is dynamic), there is extra space between items. Why?

enter image description here

I don't want this extra space, how can I "remove" it?

whitecircle
  • 237
  • 9
  • 34

2 Answers2

0

Because container height is 100vh. if you update it like height:auto, this issue will be fixed. Or items list should be wrapped by another element like below code. it's working

.container {
  width: 500px;
  height: 100vh;
  background-color: lightgrey;
  padding: 10px;
  overflow: auto;
}

.items {
  display: flex;
  flex-wrap: wrap;
}

.item {
  width: 200px;
  height: 200px;
  background-color: gold;
  border: 1px solid orange;
}
<div class="container">
  <div class="items">
    <div class="item" ></div>
    <div class="item" ></div>
    <div class="item" ></div>
    <div class="item" ></div>
    <div class="item" ></div>
    <div class="item" ></div>
    <div class="item" ></div>
  </div>
</div>
Roman Gavrilov
  • 620
  • 4
  • 17
0

When using flex-wrap: wrap, the contents are grouped into "lines" of contents known as flex lines, the align-content property controls how the flex lines are packed. In your case, setting align-content: flex-start; would achieve your needs.

visualization of align-content settings

Source W3C

.container {
  width: 500px;
  height: 100vh;
  background-color: lightgrey;
  padding: 10px;
  overflow: auto;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.item {
  width: 200px;
  height: 200px;
  background-color: gold;
  border: 1px solid orange;
}
<div class="container">
  <div class="item" ></div>
  <div class="item" ></div>
  <div class="item" ></div>
  <div class="item" ></div>
  <div class="item" ></div>
  <div class="item" ></div>
  <div class="item" ></div>
</div>

Credit: This answer is inspired by another Stack Overflow post How does flex-wrap work with align-self,align-items and align-content

Tianzhen Lin
  • 2,404
  • 1
  • 19
  • 19