以下是我的html / css:
.parent { display: flex; height: 100px; background-color: red; flex-wrap: wrap; } .child-1 { background-color: green; flex: 0.5; } .child-2 { background-color: yellow; flex: 0.5; } .child-3 { background-color: pink; }
<div class="parent"> <div class="child-1">LOREN IPSUM LOREN IPSUM</div> <div class="child-2">LOREN IPSUMLOREN IPSUMLOREN IPSUM</div> <div class="child-3">LOREN IPSUMLOREN IPSUM</div> </div>
请检查JSFiddle.
提前致谢.
解决方法
它不适用于直接或精确调整柔性物品的尺寸.
从spec:
flex-grow
… determines how much the flex item will grow relative
to the rest of the flex items in the flex container when positive free
space is distributed.
因此,flex-grow不会强制项目包装.这是flex-grow的例子:1000:demo
要定义弹性项目的长度,请使用宽度,高度或弹性基础.
解释flex-grow:0.5
当你应用flex:0.5时,你使用flex速记属性来说:
> flex-grow:0.5
> flex-shrink:1
> flex-basis:0
柔性增长组件代表一定比例.在这种情况下,它告诉flex项目消耗容器中一半的可用空间相对于其兄弟姐妹的flex-grow因子.
因此,例如,如果容器的宽度为:600px,并且三个div的总宽度为450px,则这将在可用空间中留下150px(demo).
如果每个项目都有flex-grow:1,那么每个项目将消耗50px的额外空间,并且每个项目将计算宽度:200px(demo).
但是在你的代码中,有两个项目有flex-grow:0.5,最后一个项目有flex-grow:0,所以这里是它如何分解:
- div#1 will get 75px (half of the available space)
- div#2 will get 75px (half of the available space)
- div#3 will get 0 (because its
flex-grow
is 0)
这些是现在的计算值:
- div#1 =
width: 225px
- div#2 =
width: 225px
- div#3 =
width: 150px
.parent { display: flex; flex-wrap: wrap; height: 100px; background-color: red; width: 600px; } .parent > div { flex-basis: 150px; } .child-1 { flex: 0.5; background-color: green; } .child-2 { flex: 0.5; background-color: yellow; } .child-3 { background-color: pink; }
<div class="parent"> <div class="child-1">LOREN IPSUM LOREN IPSUM</div> <div class="child-2">LOREN IPSUMLOREN IPSUMLOREN IPSUM</div> <div class="child-3"> LOREN IPSUMLOREN IPSUM</div> </div>
注意:问题的真相是,因为div#1和#2具有相同的flex-grow因子,而div#3的因子为0,所以该值无关紧要.你可以使用任何数字来代替0.5.只要它在两个div中都相同,项目将计算为225px,因为比例将是相同的.
更多信息:
> flex-grow not sizing flex items as expected
> How to get flexbox to include padding in calculations?
> What are the differences between flex-basis and width?