htmlcssflexbox

Why is flex-wrap causing gaps in cross axis when set to wrap?


So I have been learning CSS as a beginner. Recently I was exploring flex-box. My original knowledge of flex-wrap: wrap; is that if overflow occurs along the main axis (flex-direction) it prevents it by wrapping the items in the next row (suppose flex-direction: row;). What I don't seem to understand is that why it leaves gaps in the cross axis? Please see the code down below

#container {
  height: 300px;
  width: 80%;
  background-color: azure;
  margin: 10px auto;
  border: 2px solid black;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

h1 {
  text-align: center;
}

#container div {
  height: 90px;
  width: 300px;
  color: white;
  text-align: center;
  font-size: 1.5em;
}
<h1>Flexbox Playground</h1>
<div id="container">
  <div style="background-color: #9400d3">violet</div>
  <div style="background-color: #4b0082">indigo</div>
  <div style="background-color: #0000ff">blue</div>
  <div style="background-color: #00ff00">green</div>
  <div style="background-color: #ffff00">yellow</div>
  <div style="background-color: #ff7f00">orange</div>
  <div style="background-color: #ff0000">red</div>
</div>

So since my initial item height was 100px, I did not see anything wrong in the cross axis. But then I tried to reduce the height of the item from 100px to 50px, I saw gaps in the cross axis (vertical direction). I wasn't expecting this and couldn't understand what was causing this behavior. I am attaching pics for reference. First one is when height of the item is 100px: first_image and second one is when the height has been reduced to 50px: second_image


Solution

  • This is because the default value of align-content is stretch to spread the divs across the height of the parent.

    It needs to be set to start.

    #container {
      height: 300px;
      width: 80%;
      background-color: azure;
      margin: 10px auto;
      border: 2px solid black;
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      align-content: start;
    }
    
    h1 {
      text-align: center;
    }
    
    #container div {
      height: 90px;
      width: 25%;
      color: white;
      text-align: center;
      font-size: 1.5em;
    }
    
    * {
      margin: 0;
      padding: 0;
      min-width: 0;
      min-height: 0;
      box-sizing: border-box;
    }
    <div id="container">
      <div style="background-color: #9400d3">violet</div>
      <div style="background-color: #4b0082">indigo</div>
      <div style="background-color: #0000ff">blue</div>
      <div style="background-color: #00ff00">green</div>
      <div style="background-color: #ffff00">yellow</div>
      <div style="background-color: #ff7f00">orange</div>
      <div style="background-color: #ff0000">red</div>
    </div>