要设置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方法 在这里:

我拒绝的一个想法是去掉外部列的填充物,就像这样:

div:nth-child(#{$col-number}n+1) { padding-left: 0; }
div:nth-child(#{$col-number}n+#{$col-number}) { padding-left: 0; }

但是,像这里的其他海报一样,我更喜欢负边距技巧。我的小提琴也有响应任何人正在寻找一个基于sass的解决方案。我基本上使用这种方法来代替网格。

https://jsfiddle.net/x3jvfrg1/

其他回答

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

#箱{ 显示: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 >

这并不适用于所有情况,但如果你有灵活的子宽度(%),并且知道每行有多少项,你可以通过使用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 >

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

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

#box {
   display: flex;
}

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

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

这是我的解决方案,它不需要在子元素上设置任何类:

.flex-inline-row {
    display: inline-flex;
    flex-direction: row;
}

.flex-inline-row.flex-spacing-4px > :not(:last-child) {
    margin-right: 4px;
}

用法:

<div class="flex-inline-row flex-spacing-4px">
  <span>Testing</span>
  <span>123</span>
</div>

除了上面给出的内联示例之外,同样的技术还可以用于普通的flex行和列,并扩展了除4px以外的间距类。

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

.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 >