要设置flexbox项目之间的最小距离,我使用margin: 0 5px on .item和margin: 0 -5px on container。对我来说,这似乎是一种hack,但我找不到更好的方法来做到这一点。

#箱{ 显示:flex; 宽度:100 px; Margin: 0 -5px; } .item { 背景:灰色; 宽度:50 px; 高度:50 px; 边距:0 5px; } < div id =“盒子”> < div class = '物品' > < / div > < div class = '物品' > < / div > < div class = '物品' > < / div > < div class = '物品' > < / div > < / div >


当前回答

我已经找到了一个基于一般兄弟选择器~的解决方案,并允许无限嵌套。

有关工作示例,请参阅此代码笔

基本上,在列容器中,前面有另一个子容器的每一个子容器都有上边距。同样,在每个行容器中,前面有另一个子容器的子容器都有左边距。

.box { 显示:flex; flex-grow: 1; flex-shrink: 1; } .box。列{ flex-direction:行; } .box.columns > .box ~。盒子{ margin-left: 5 px; } .box。行{ flex-direction:列; } .box.rows > .box ~。盒子{ margin-top: 5 px; } <div class="box columns"> < span style=" font - family:宋体;"> < / div > <div class="box rows"> <div class="box rows"> < span style=" font - family:宋体;"> < / div > < span style=" font - family:宋体;"> < / div > <div class="box columns"> < span style=" font - family:宋体;"> < / div > < span style=" font - family:宋体;"> < / div > < / div > < / div > < span style=" font - family:宋体;"> < / div > < / div > < / div >

其他回答

我之前遇到过同样的问题,然后偶然发现了这个问题的答案。希望对大家有所帮助,供今后参考。

长话短说,给孩子的弹性物品添加边框。 然后,您可以指定flex项之间的空白。 在代码片段中,我使用黑色来说明,如果你喜欢,你可以使用“透明”。

#箱{ 显示:flex; 宽度:100 px; /* margin: 0 -5px;*删除* / } .item { 背景:灰色; 宽度:50 px; 高度:50 px; /* margin: 0 5px;*删除* / 边框:1px纯黑色;/*添加这个*/ } .item。特殊{边距:0 10px;} < div id =“盒子”> < div class = '物品' > < / div > < div class = '物品' > < / div > < div class = '物品' > < / div > < div class = '物品' > < / div > <div class='item special'></div> < / div >

博士tl;

$gutter: 8px;

.container {
  display: flex;
  justify-content: space-between;

  .children {
    flex: 0 0 calc(33.3333% - $gutter);
  }
}

这并不适用于所有情况,但如果你有灵活的子宽度(%),并且知道每行有多少项,你可以通过使用n -child selector/s非常清楚地指定必要元素的边距。

这很大程度上取决于你对“更好”的定义。这种方法不需要为子元素或负元素添加额外的包装器标记——但它们都有自己的位置。

.container { align-content: flex-start; 对齐项目:伸展; background - color: # ccc; 显示:flex; Flex-flow:行换行; justify-content: flex-start; 宽度:100%; } .child-item { background - color: # c00; margin-bottom: 2%; 最小高度:5 em; 宽度:32%; } .child-item: nth-child (3 n - 1) { margin-left: 2%; margin-right: 2%; } < div class = "容器" > < div class = " child-item " > < / div > < div class = " child-item " > < / div > < div class = " child-item " > < / div > < div class = " child-item " > < / div > < div class = " child-item " > < / div > < div class = " child-item " > < / div > < div class = " child-item " > < / div > < / div >

根据#ChromeDevSummit的说法,在Firefox和基于chrome的浏览器中,Flexbox有一个gap属性的实现。

这是一个现场演示

在这种情况下,我经常使用+运算符

#箱{ 显示:flex; 宽度:100 px; } .item { 背景:灰色; 宽度:50 px; 高度:50 px; } .item + .item { margin-left: 5 px; } < div id =“盒子”> < div class = '物品' > < / div > < div class = '物品' > < / div > < div class = '物品' > < / div > < div class = '物品' > < / div > < / div >