这是字节跳动的的一道面试题。css
* {
padding: 0;
margin: 0;
}
.container {
width: 600px;
height: 300px;
display: flex;
}
.left {
width: 500px;
flex-shrink: 2;
background: red;
}
.right {
width: 400px;
flex-shrink: 1;
background: blue;
}
复制代码
求最终left和right的宽度。面试
先看实际展现的效果bash
left: 285.72px
right: 314.28px
复制代码
从上面的结果来看,当子容器宽度之和超出父容器宽度以后不是仅仅按照500:400 或者 2:1来计算的,实际计算过程应该是这个样子的:布局
咱们加上paddingflex
* {
padding: 0;
margin: 0;
}
.container {
width: 600px;
height: 300px;
display: flex;
}
.left {
width: 500px;
padding: 40px;
flex-shrink: 2;
background: red;
}
.right {
width: 400px;
padding: 20px;
flex-shrink: 1;
background: blue;
}
复制代码
实际效果是:flexbox
left: 280px
right: 320px
复制代码
先想一想结果为何会变化?spa
缘由是code
box-sizing
时,其默认值是content-box
,也就是标准盒模型,盒子的宽是不包括padding
、border
的,因此若是不考虑父容器的宽度,left真正占据的空间应该是500 + 40x2 = 580, 而right则是:400 + 40x2=440。下面是w3c对flex布局中可用空间的描述get
w3c: Determine the available main and cross space for the flex items. For each dimension, if that dimension of the flex container’s content box is a definite size, use that; if that dimension of the flex container is being sized under a min or max-content constraint, the available space in that dimension is that constraint; otherwise, subtract the flex container’s margin, border, and padding from the space available to the flex container in that dimension and use that value. This might result in an infinite value.it
这里提到flex项的可用空间要减去margin、border、padding。
因此这里计算的过程就是:
ok,那咱们再看看 box-sizing: border-box
的状况
* {
padding: 0;
margin: 0;
}
.container {
width: 600px;
height: 300px;
display: flex;
}
.left {
width: 500px;
padding: 40px;
flex-shrink: 2;
background: red;
box-sizing: border-box;
}
.right {
width: 400px;
padding: 20px;
flex-shrink: 1;
background: blue;
box-sizing: border-box;
}
复制代码
实际效果是
left: 290px
right: 310px
复制代码
当咱们设置box-sizing: border-box
,也就是IE盒模型,盒子的宽是包括padding
、border
的,若是不考虑父容器宽度的话,left真正占据的空间依然是500 right是400,padding依然不能参与分配,那么left、right的可用空间分别就变成了500-40x2=420, 400-20x2=360, 因此这里计算的过程就是:
咱们总结一下计算过程