要设置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 >


当前回答

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

长话短说,给孩子的弹性物品添加边框。 然后,您可以指定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 >

其他回答

我发现最简单的方法就是用百分比来计算,然后让页边距来计算宽度

这意味着如果你使用你的例子,你最终会得到这样的结果

#box {
   display: flex;
}

.item {
   flex: 1 1 23%;
   margin: 0 1%;
}

这意味着你的值是基于宽度的,虽然这可能对每个人都不好。

你可以试试CSS3的:not选择器

Eg:

#箱{ 显示:flex; 宽度:100 px; 边框:1px红色实体; } .item { 背景:灰色; 宽度:10 px; 身高:100 px; Flex: 1台自动; } .item:没有(胎){ margin-right: 5 px; } < div id =“盒子”> < div class = '物品' > < / div > < div class = '物品' > < / div > < div class = '物品' > < / div > < div class = '物品' > < / div > < / div >

博士tl;

$gutter: 8px;

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

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

我用了另一种方法。在容器上使用负边距,这需要与每个子容器相同,例如10px。 然后对每个子元素使用calc()减少每边的总边距宽度,在本例中为20px。

这里有一个例子:https://codepen.io/anon/pen/KJLZVg

这有助于响应地处理事情,因为您不需要针对特定的第n个子以保持它在包装时在容器的每一侧保持齐平。

.parent {
    padding: 0 10px;
}
.container {
    display: flex;
    margin: 0 -10px;
    flex-wrap: wrap;
    width: 100%;
    max-width: 500px;
    margin: 0 auto;
}
.child {
    margin: 0 10px 25px 10px;
    flex: 0 0 calc(25% - 20px);
    height: 40px;
    background: red;
}

<div class="parent">
<div class="container">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
</div>

同样使用flex: 0 0(宽度),它有助于IE浏览器。

更新:缝隙的flexbox现在支持所有现代浏览器(Edge/Chrome/Opera/三星互联网/Safari/Firefox)

最终,他们将把gap属性添加到flexbox中。在此之前,你可以使用CSS网格代替已经有间隙属性,只有一行。比处理边距要好。