如何设置flex两行之间的间距?

<div class="flex">
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
</div> 

分成两行,怎么设置两行之间的间距?

之前见到一种方法是设置.flex-itemmargin-bottom:10px,然后用父容器.flexmargin-bottom: -10px;来抵消。
这里有一个问题是这样就不能设置父容器的margin-bottom了。

请问有什么办法?

阅读 67.2k
6 个回答

1.父容器定高的情况:
计算好需要的总高度,父容器只要align-content: space-between即可,浏览器自动推算出中间的间距;

2.父容器不定高的情况:
使用上面抵消的方法,至于上下的外边距,只能通过相邻的元素来间接设置了。

父容器 align-content: space-between;

设置.flex-itemmargin-top: 10px,然后用.flex-item:last-child, .flex-item:nth-last-child(2)margin-bottom: 0将最后两个子元素的margin-bottom去掉。

新手上路,请多包涵

.flex-item {margin-bottom: 10px}
.flex {padding-top: 10px}

.flex-item{
   margin-top: 10px 
}
.flex-item:nth-type-of(1),.flex-item:nth-type-of(2){
   margin-top: 0; 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题