1、当主轴空间有剩余,求最终left、right宽度
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
<style>
* {
padding: 0;
margin: 0;
}
.container {
width: 600px;
height: 300px;
display: flex;
}
.left {
flex: 1 2 300px;
background: red;
}
.right {
flex: 2 1 200px;
background: blue;
}
</style>
计算规则:
剩余空间:
600-(300+200)= 100px
flex-grow值分别为1和2
,总共3等分,left: 1/3
,right: 2/3
最终的值:(flex-basis + 剩余 * flex-grow占比)
left:
300+100 * 1/3 = 333.33px
right:
200+100* 2/3 = 266.67px
2、当主轴空间不足,求最终left、right宽度
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
<style>
* {
padding: 0;
margin: 0;
}
.container {
width: 600px;
height: 300px;
display: flex;
}
.left {
flex: 1 2 500px;
background: red;
}
.right {
flex: 2 1 400px;
background: blue;
}
</style>
计算规则:
flex-shrink的值分别为2和1
溢出空间:
(500+400)- 600 = 300px
总权重:
2 * 500 + 1 * 400 = 1400
缩小的空间值:(溢出 * flex-shrink * 权重占比)
left:
300 * 2 * 500/1400 = 214.28px
right:
300 * 1 * 400/1400 = 85.72px
最终的值:
left:500 - 214.28 = 285.72
right:400 - 85.72 = 314.28