Flexbox: how to add margin / vertical spacing for the case there is more than one row?

五迷三道 提交于 2020-01-05 01:07:10

问题


here is the codepen

I want to add vertical spacing ONLY to elements between line 1 and line 2. Alternatively, only to between line 1 and line 2, and line 2 and line 3.

The flex items are random, so the amount, size of each, is dynamic.

I cannot add margins to all, because that would ruin the layout in case there is no second row at all.

HTML

<div class="flexContainer">
  <div class="flexItem">a a a aaaaaaa a ax</div>
  <div class="flexItem">bbbx</div>
  <div class="flexItem">c c  c c c cx</div>
  <div class="flexItem">note: random amount of flex items</div>
    <div class="flexItem">amount can very...</div>
</div>

<br/><br/><br/>
<div class="flexContainer">
  <div class="flexItem">a a a aaaaaaa a ax</div>
  <div class="flexItem">bbbx</div>
  <div class="flexItem">c c  c c c cx</div>
</div>

CSS

.flexContainer{
  background-color: salmon;
  display: flex;
  flex-direction: row;
  width: 300px;
  flex-wrap: wrap;
}

.flexItem{
  background-color: lightblue;
  margin: 5px;
}

Browsersupport: only newest cutting edge browsers are supported.


回答1:


You can

  • Add some margin-bottom to the first and last .flex-items.
  • Align all flex items to top with align-items: flex-start or align-self: flex-start.
  • Add a negative margin-bottom to .flexContainer in order to counteract the margin after the last line.
  • Place the .flexContainer inside a wrapper with overflow: hidden.

.wrapper {
  overflow: hidden;
}
.flexContainer {
  background-color: salmon;
  display: flex;
  flex-flow: row wrap;
  width: 300px;
  margin-bottom: -20px; /* 25-20 = 5 */
}
.flexItem {
  background-color: lightblue;
  margin: 5px;
  align-self: flex-start;
}
.flexItem:first-child, .flexItem:last-child {
  margin-bottom: 25px;
}
<div class="wrapper">
  <div class="flexContainer">
    <div class="flexItem">a a a aaaaaaa a ax</div>
    <div class="flexItem">bbbx</div>
    <div class="flexItem">c c  c c c cx</div>
    <div class="flexItem">note: random amount of flex items</div>
    <div class="flexItem">amount can very...</div>
  </div>
</div>
<br/><br/>
<div class="wrapper">
  <div class="flexContainer">
    <div class="flexItem">a a a aaaaaaa a ax</div>
    <div class="flexItem">bbbx</div>
    <div class="flexItem">c c  c c c cx</div>
  </div>
</div>


来源:https://stackoverflow.com/questions/31844421/flexbox-how-to-add-margin-vertical-spacing-for-the-case-there-is-more-than-on

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!