這是字節跳動的的一道面試題。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, 因此這裏計算的過程就是:
咱們總結一下計算過程