Search code examples
htmlcssflexboxvertical-alignment

Cant get my flex items to wrap correctly. They are not lining up underneath the first row correctly


As you can see if you run my snippet, the second row is being positioned in the middle of literally nowhere for no reason that I can explain. I want it to be right underneath the first row with a 0.5rem gap. I want to achieve this while still keeping the height of the container as minimum 3 item heights like I have it. Please help

.grid_product_images {
  --gpi-item-size: 6rem;
  --gpi-gap: 0.5rem;
  --gpi-columns: 3;
  display: flex;
  flex-wrap: wrap;
  /* grid-template-columns: repeat(var(--gpi-columns), 1fr); */
  gap: var(--gpi-gap);
  max-width: calc(calc(var(--gpi-item-size) * var(--gpi-columns)) + calc(var(--gpi-gap) * calc(var(--gpi-columns) + 1)));
  min-height: calc(calc(var(--gpi-item-size) * var(--gpi-columns)) + calc(var(--gpi-gap) * calc(var(--gpi-columns) + 1)));
  align-items: flex-start;
  padding: var(--gpi-gap);
  border-radius: 0.5rem;
  background-color: grey;
}
.grid_product_images > div {
  width: var(--gpi-item-size);
  height: var(--gpi-item-size);
  border-radius: 0.5rem;
  background-color: white;
  box-shadow: 0 1px 2px 0 rgba(0,0,0,0.2);
  cursor: pointer;
}
.grid_product_images .btn_add_image {
  width: 100%;
  height: 100%;
  background-color: white;
  border: 0.1rem solid black;
  border-radius: 0.5rem;
  cursor: pointer;
}
<div class='grid_product_images'>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div class='add_image_container'>
    <button type='button' class='btn_add_image' id='btn_add_image'>+</button>
  </div>
</div>


Solution

  • Try setting align-content: flex-start; in your flex container.

    As per MDN:

    The CSS align-content property sets the distribution of space between and around content items along a flexbox's cross-axis or a grid's block axis.