给包装好的柔性盒子垂直间距

我最近第一次使用 Flexbox,总的来说,它非常棒。然而,我最近遇到了一个问题,我似乎不能给弹性项目包装任何垂直间距。

我试过用:

align-content: space-between;

但这好像没什么用。从我已经完成的阅读来看,这似乎只有当我的 flex 容器高于其中包含的元素时才会起作用(是这样吗?)如果是这样,那么我是否应该为我的弹性容器设置一个高度,这似乎违背了使用弹性容器的目的?

我能想到的唯一办法就是给内部的元素留出底部空间,但这似乎又一次违背了我的初衷。

希望我遗漏了一些相当明显的东西——这里有一个到 codeen 的链接: http://codepen.io/lordchancellor/pen/pgMEPz

还有,这是我的密码:

HTML:

<div class="container">
<div class="col-sm-12">
<h1>Flexbox Wrapping</h1>


<div class="flexContainer">
<div class="flexLabel">This is a flex label</div>
                    

<a class="btn btn-primary">Button 1</a>
<a class="btn btn-warning">Button 2</a>
<a class="btn btn-success">Button 3</a>
</div>
</div>
</div>

CSS:

.flexContainer {
display: flex;
flex-wrap: wrap;
align-items: center;
align-content: space-between;
justify-content: center;
}
.flexContainer .flexLabel {
flex-basis: 150px;
flex-shrink: 0;
}

编辑-只是要在这里添加一点更多的细节,因为我不确定我是否能够很好地理解它。

在我的大型项目中,我有一些块级元素,它们被安排在一行使用柔性箱。但是,需要有一些响应,因为用户可能会减少屏幕宽度。此时,我希望我的元素开始堆栈(因此进行了包装)。然而,当元素开始堆叠时,它们都垂直接触,我希望这里有间隔。

这看起来似乎是解决这个问题的唯一方法——不过我想知道是否有一种以弹性工具箱为中心的方法来实现这一点。

107610 次浏览

It's because you don't have a height on your flex content for it to calculate the space-between so at the moment, the flex container is as small as possible. Add a height and it should work.

If you force wrapping by applying a width you can then use margins as you normally would without setting a height.

.flexContainer {
display: flex;
align-items: center;
flex-wrap: wrap;
justify-content: center;
background: pink;
width: 150px;
}
.flexContainer > * {
margin: 1em 0;
}
.flexContainer .flexLabel {
flex-basis: 150px;
flex-shrink: 0;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />


<div class="container">
<div class="col-sm-12">
<h1>Flexbox Wrapping</h1>


<div class="flexContainer">


<div class="flexLabel">This is a flex label</div>


<a class="btn btn-primary">Button 1</a>
<a class="btn btn-warning">Button 2</a>
<a class="btn btn-success">Button 3</a>
</div>


</div>
</div>

I had a similar issue and I used the following hack to solve the issue.

    /* add a negative top-margin to the flex container */
.flexContainer {
/* ... your existing flex container styles here */
margin: -10px 0 0 0;
}
/* add a corresponding positive top margin to all flex items (all direct children of the flex container) */
.flexContainer > * {
margin-top: 10px;
}

For the top row of flex items the negative and positive margins cancel out, for the subsequent rows it adds the margin between the rows (in this case 10px between rows).

It's less than elegant but it gets the job done.

Another hacky solution is to give the item a bottom border:

border-bottom: 10px solid transparent;

row-gap would solve your problem

.flexbox {
display: flex;
column-gap: 10px;
row-gap: 10px
}