在盒子中嵌套多个盒子时,明明内部的盒子加起来不会超过最外层盒子的尺寸,但是在缩小浏览器界面时却有盒子被挤出去了。
这是因为在标准盒子中width +padding + border 一起决定盒子的宽或高,例如下面所示代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.big{
margin: 100px auto;
width: 200px;
height: 100px;
background-color: blue;
}
.left{
float: left;
width: 100px;
height: 100px;
background-color: orange;
}
.right{
float: left;
width: 98px;
height: 100px;
background-color: yellow;
border: 1px solid grey;
}
</style>
</head>
<body>
<div class="big">
<div class="left">left</div>
<div class="right">right</div>
</div>
</body>
</html>
运行后出现如下情况(此时浏览器显示比例为100%):
最底下的大盒子(类名为big,背景颜色为蓝色)此时已经完全被内部的left盒子和right盒子所覆盖,从代码可以看出big盒子宽为200px,left盒子宽度为100px,right盒子宽度为98px,再加上right盒子左右边框1px,刚刚好等于big盒子的宽。所以刚刚好覆盖掉big盒子。但是当缩小浏览器视图,出现如下情况:
可以看到right盒子掉下去了。这是因为这时浏览器视图变成原来的50%,此时big盒子宽度就从200px变成了100px,left盒子的宽度也缩小到原来(100px)的一半,也就是50px,right盒子也缩小到原来(98px)的一半,也就是49px,但是right的边框设置的是1px,已经达到最小像素,无法缩小了,所以边框不变,仍为1px,左右边框加起来就是2px,此时内部的盒子宽度加起来就是50+49+2=101px,已经超出了big盒子的100px,所以right盒子无法被big盒子容纳,就掉下去了。
解决这个问题需要借助怪异盒子模型。怪异盒模型中,宽度和高度就是我们设置的width和height,只要在right盒子的css样式中加上一行代码box-sizing:border-box。具体如下方代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.big{
margin: 100px auto;
width: 200px;
height: 100px;
background-color: blue;
}
.left{
float: left;
width: 100px;
height: 100px;
background-color: orange;
}
.right{
float: left;
width: 98px;
height: 100px;
background-color: yellow;
border: 1px solid grey;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="big">
<div class="left">left</div>
<div class="right">right</div>
</div>
</body>
</html>
结果如下图:
可以看出,此时浏览器视图仍然是50%,因为使用的怪异盒,所以left盒子加上right盒子宽度仅有98px,而big盒子有100px,right盒子并没有掉下去。从上面图中还能看出2px的蓝色部分。