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


当前回答

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

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

其他回答

#箱{ 显示:flex; 宽度:100 px; } .item { 背景:灰色; 宽度:50 px; 高度:50 px; } /* u表示效用*/ .u-gap-10 > *:not(:last-child) { margin-right: 10 px; } <div id='box' class="u-gap-10"> < div class = '物品' > < / div > < div class = '物品' > < / div > < div class = '物品' > < / div > < div class = '物品' > < / div > < / div >

一个带有-x(负)边距的伸缩容器和带有x(正)边距或填充的伸缩项都会导致预期的视觉结果:伸缩项之间只有2x的固定间距。

这似乎只是一个偏好问题,是在伸缩项上使用边距还是填充。

在这个例子中,为了保持固定的间隙,伸缩项是动态缩放的:

.flex-container { 
  margin: 0 -5px;
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

.flex-item {
  margin: 0 5px; // Alternatively: padding: 0 5px;
  flex: 1 0 auto;
}

Flexbox的利润率并没有下降。 Flexbox没有任何类似于表的边界间距(编辑:CSS属性差距在较新的浏览器中实现了这一角色,我可以使用吗)

因此,实现你的要求有点困难。

根据我的经验,不使用:first-child/:last-child,并且对flex-wrap:wrap不做任何修改的“最干净”的方法是在容器上设置padding:5px,在子元素上设置margin:5px。这将在每个子元素之间以及每个子元素与其父元素之间产生10px的间隙。

Demo

.upper { 保证金:30 px; 显示:flex; flex-direction:行; 宽度:300 px; 身高:80 px; 边框:1px红色实体; 填充:5 px;/* this */ } .upper > div { Flex: 1台自动; 边框:1px红色实体; text-align:中心; 保证金:5 px;/*,这将导致10px的差距*/ } .upper。MC /* multicol test */ { flex-direction:列; flex-wrap:包装; 宽度:200 px; 身高:200 px; } < div class = "上" > < div > 3 < br / > aaa < / div > < div > 3 < / div > < div > 3 < br / > aaa < / div > < div > 3 < br / > aaa < br / > aaa < / div > < div > 3 < / div > < div > 3 < / div > < / div > <div class="上MC "> < div > 3 < br / > aaa < / div > < div > 3 < / div > < div > 3 < br / > aaa < / div > < div > 3 < br / > aaa < br / > aaa < / div > < div > 3 < / div > < div > 3 < / div > < / div >

盒子容器上的负边距技巧效果很好。这是另一个例子,工作的秩序,包装和什么不。

.container { 边框:1px纯绿色; 宽度:200 px; 显示:inline-block; } #箱{ 显示:flex; flex-wrap: wrap-reverse; 保证金:-10 px; 边框:1px纯红色; } .item { Flex: 1台自动; 顺序:1; 背景:灰色; 宽度:50 px; 高度:50 px; 保证金:10 px; 边框:1px纯蓝色; } 当代{ 秩序:0; } < div class =容器> < div id =“盒子”> < div class = '物品' > 1 < / div > < div class = '物品' > < / div > 2 <div class='item first'>3*</div> 4 < div class = '物品' > < / div > < div class = '物品' > < / div > 5 < / div > < / div >

博士tl;

$gutter: 8px;

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

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