CSS3中采用弹性盒中弹性项目的压缩规则
默认情况下,当弹性盒空间不足时,弹性项目会相应压缩,当具体的压缩规则是什么呢?我们来看一个示例
<style>
.contain {
width: 300px;
height: 300px;
background: red;
display: flex;
}
.item1 {
width: 200px;
height: 200px;
background: green;
flex-shrink: 1
}
.item2 {
width: 400px;
height: 200px;
flex-shrink: 2;
background: blue;
}
</style>
<body>
<div class="contain">
<div class="item1"></div>
<div class="item2"></div>
</div>
</body>
得到的结果是item1的宽度为140px,item2的宽度为160px,也就是说,item1的压缩值是60px,item2的压缩值为240px。压缩值算法如下:
加权值 = 每个弹性项目的实际内容宽度 * 压缩比例 之和
压缩值 = 弹性项目的实际内容宽度 压缩比例 弹性盒超出宽度 / 加权值
将上面的示例来演算一下:
弹性盒超出宽度 = 200 + 400 - 300 = 300
加权值 = 200 1 + 400 2 = 1000
item1压缩值 = 200 1 300 / 1000 = 60
item2压缩值 = 400 2 300 / 1000 = 240
注意:计算加权值一定要代入弹性项目的实际内容宽度,也就是内容区的宽度。
例如:
<style>
*{
box-sizing:border-box;
}
.contain {
width: 300px;
height: 300px;
background: red;
display: flex;
}
.item1 {
width: 200px;
height: 200px;
background: green;
flex-shrink: 1;
padding:0 50px;
}
.item2 {
width: 400px;
height: 200px;
flex-shrink: 2;
background: blue;
}
</style>
<body>
<div class="contain">
<div class="item1"></div>
<div class="item2"></div>
</div>
</body>
得到的结果为item1的宽度为166.67px,item2的宽度为133.33px。也就是说item1的压缩值为33.33px,item2的压缩值为266.67px。我们用上述公式求一下压缩值:
加权值 = 100 1 + 400 2 = 900
item1压缩值 = 100 1 300 / 900 = 33.33
item2压缩值 = 400 2 300 / 900 = 266.67
用公式求出来的结果与真实结果一致。所以在默认情况下,当弹性盒空间不足时,弹性项目的压缩规则如下:
加权值 = 每个弹性项目的实际内容宽度 * 压缩比例 之和
压缩值 = 弹性项目的实际内容宽度 压缩比例 弹性盒超出宽度 / 加权值
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。