12

Here's my example code:

#parent {
  display: flex;
  height: 350px;
  background: yellow;
}
#wrapper {
  flex: 1;
  display: flex;
  flex-flow: row wrap;
  margin: 0 10%;
  background: #999;
}

#top {
  flex: 1 100%;
  height: 50px;
  margin-top: 10px;
  background: red;
}

#left {
  width: 30%;
  height: 150px;
  margin: 10px 10px 0 0;
  background: blue;
}

#right {
  flex: 1;
  margin: 10px 0 0 0;
  background: green;
}
<div id="parent">
  <div id="wrapper">
    <div id="top"></div>
    <div id="left"></div>
    <div id="right"></div>
  </div>
</div>

As you can see, there's a gap (big gray area) between top (red) and left/right (blue/green). Flexbox seems to be spreading everything equally in parent element (gray).

However, I don't want the gap between my elements, I need everything to "rise" to top. There can be a gap after all elements (at the end).

I tried everything I could find/think of: auto margins, justify-content, align-items etc. No desired effect.

How to achieve this?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Solo
  • 6,687
  • 7
  • 35
  • 67

2 Answers2

22

You need to add align-content: flex-start on flex-container or in your case #wrapper element.

#parent {
  display: flex;
  height: 350px;
  background: yellow;
}
#wrapper {
  flex: 1;
  display: flex;
  flex-flow: row wrap;
  margin: 0 10% 50px 10%;
  background: #999;
  align-content: flex-start; /* Add this*/
}
#top {
  flex: 1 100%;
  height: 50px;
  margin-top: 10px;
  background: red;
}
#left {
  width: 30%;
  height: 150px;
  margin: 10px 10px 0 0;
  background: blue;
}
#right {
  flex: 1;
  margin: 10px 0 0 0;
  background: green;
}
<div id="parent">
  <div id="wrapper">
    <div id="top"></div>
    <div id="left"></div>
    <div id="right"></div>
  </div>
</div>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
2

In a multi-line flex row layout, the align-content controls how the flex items aligns vertical when they wrap, and since its default is stretch, this is expected behavior.

Change it to align-content: center; and you'll see how their alignment change to vertical middle.

#parent {
  display: flex;
  height: 350px;
  background: yellow;
}
#wrapper {
  flex: 1;
  display: flex;
  flex-flow: row wrap;
  margin: 0 10% 50px 10%;
  background: #999;
  align-content: center;
}

#top {
  flex: 1 100%;
  height: 50px;
  background: red;
}

#left {
  width: 30%;
  height: 150px;
  background: blue;
}
#right {
  flex: 1;
  background: green;
}
<div id="parent">
  <div id="wrapper">
    <div id="top"></div>
    <div id="left"></div>
    <div id="right"></div>
  </div>
</div>
Asons
  • 84,923
  • 12
  • 110
  • 165