在弹性项目上使用边距 [英] Using margin on flex items
问题描述
我的印象是,可以向弹性项目/子项添加边距,flexbox应该自动考虑这一点,并计算项目之间的正确间距。
这里提供了 https://jsfiddle.net/dba5ehcw/1/
。 flex-item {
border:1px solid blue;
box-sizing:border-box;
height:160px;
width:50%;
}
现在,每个flex项目都是容器宽度的一半,他们彼此流动很好。
我想在弹性物品上增加一个说法边缘1em,以给他们一些喘息的空间,但是在这样做时,它们变得大于50%,并且不再在同一行上彼此堆叠,因为它们太宽。
为了在flex-items上使用margin,并且让flexbox容器考虑这一点,并相应地调整(减少)它们的宽度?
你需要使用填充 - 当 border-box
模式不会使容器大于其指定的宽度 - 不是边距,而是嵌套 flex
div。这就是所有基于flexbox的网格系统的工作原理。以下代码:
.flex-container {border:1px solid red; box-sizing:border-box;显示:flex; flex-wrap:wrap; width:320px;}。flex-item {padding:1em; box-sizing:border-box; height:160px; width:50%; display:flex;}。flex-item> div {border:1px solid blue; flex:1 1 auto;}
< div class = flex-container> < div class =flex-item>< div>< / div>< / div> < div class =flex-item>< div>< / div>< / div> < div class =flex-item>< div>< / div>< / div> < div class =flex-item>< div>< / div>< / div> < div class =flex-item>< div>< / div>< / div> < div class =flex-item>< div>< / div>< / div>< / div>
/ div>
I was under the impression that a margin can be added to flex items/children, and flexbox should automatically take that into account and calculate the correct spacing between the items.
I can't seem to get this working as I would like though.
Fiddle here: https://jsfiddle.net/dba5ehcw/1/
.flex-item{
border: 1px solid blue;
box-sizing: border-box;
height: 160px;
width: 50%;
}
So each flex item at the moment is half the width of the container, and they flow nicely next to each other.
I would like to be able to add a margin of say, 1em to the flex-items in order to give them some breathing room, but in doing so, they become larger than the 50% and no longer stack next to each other on the same line because they are too wide.
Is there a way to use margin on the flex-items and have the flexbox container take this into account and adjust (decrease) their widths accordingly?
You need to do it with padding - which, when in border-box
mode does not make the container larger than it's specified width - not margin, and a nested flex
div. This is how all flexbox-based grid systems work. Code below:
.flex-container{
border: 1px solid red;
box-sizing: border-box;
display: flex;
flex-wrap: wrap;
width: 320px;
}
.flex-item{
padding:1em;
box-sizing: border-box;
height: 160px;
width: 50%;
display:flex;
}
.flex-item>div {
border: 1px solid blue;
flex: 1 1 auto;
}
<div class="flex-container">
<div class="flex-item"><div></div></div>
<div class="flex-item"><div></div></div>
<div class="flex-item"><div></div></div>
<div class="flex-item"><div></div></div>
<div class="flex-item"><div></div></div>
<div class="flex-item"><div></div></div>
</div>
这篇关于在弹性项目上使用边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!