控制在flex容器中垂直排列的flex项的宽度 [英] Control width of flex items arranged vertically in a flex container
问题描述
我正在尝试达到以下效果:标有"HALF"的框仅占据宽度的50%(又称它们平均分配第一行).
I'm trying to achieve the effect where the boxes labeled "HALF", take up only 50% of the width (aka they share the first row evenly).
基本要求是将它们保留在单个容器中.使用flexbox是否可以实现?
The base requirement is that they remain in a single container. Is this possible to achieve using flexbox?
我尝试过使用flex-grow
,flex-shrink
和flex-basis
,但是考虑到单个容器的要求,恐怕我不了解如何使其工作,甚至可能.
I've tried playing around with flex-grow
, flex-shrink
, and flex-basis
but I'm afraid I'm not understanding how to make it work, or if it's even possible, given the single container requirement.
考虑这个小提琴: http://jsfiddle.net/GyXxT/270/
div {
border: 1px solid;
}
.container {
width: 400px;
display: flex;
flex-direction: column;
}
.child {
height: 200px;
}
.child.half {
flex: 1 1 10em;
color: green;
}
.child:not(.half) {
flex-shrink: 2;
flex-basis: 50%;
color: purple;
}
<div class="container">
<div class="child half">
HALF
</div>
<div class="child half">
HALF
</div>
<div class="child">
FULL
</div>
<div class="child">
FULL
</div>
<div class="child">
FULL
</div>
<div class="child">
FULL
</div>
</div>
推荐答案
而不是flex-direction: column
,您可以使用flex-wrap: wrap
尝试 wrapping flexbox;您可以设置:
Instead of flex-direction: column
, you can try a wrapping flexbox using flex-wrap: wrap
; and you can set:
-
flex-basis: 50%
表示半格div
flex-basis: 100%
表示全格div
看到使用 flex-basis 时,我已经抛出box-sizing: border-box
来调整宽度.
See that I have thrown in box-sizing: border-box
to adjust for the widths when using flex-basis.
请参见下面的演示
div {
border: 1px solid;
box-sizing: border-box;
}
.container {
width: 400px;
display: flex;
flex-wrap: wrap;
}
.child {
height: 200px;
}
.child.half {
flex-basis: 50%;
color: green;
}
.child:not(.half) {
flex-basis: 100%;
color: purple;
}
<div class="container">
<div class="child half">
HALF
</div>
<div class="child half">
HALF
</div>
<div class="child">
FULL
</div>
<div class="child">
FULL
</div>
<div class="child">
FULL
</div>
<div class="child">
FULL
</div>
</div>
这篇关于控制在flex容器中垂直排列的flex项的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!