核心代码
box-sizing: border-box;
代码说明:此代码可以将一个div的边框设置为内边框。
案例说明
运行以下代码:
<!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>
.divFather{
width: 200px;
height: 300px;
background-color: blue;
border: 1px solid;
}
.divSon{
width: 100px;
height: 100px;
border: 1px solid;
}
</style>
</head>
<body>
<div class="divFather">
<div class="divSon" style="background-color: red;"></div>
<div class="divSon" style="background-color: green"></div>
</div>
</body>
</html>
运行效果如下:
现在我们将红色和绿色的div添加浮动,
按道理来说:
红色div和绿色div的宽度均为100px,蓝色div宽度为200px
100px + 100px = 200px
所以按道理来说,蓝色div的宽度刚好可以容下红色div和绿色div
也就是我们预期的运行效果应该是下图中的样子:
但实际上,并不能达到预期的效果,绿色的div依然在红色的div下面(和没有设置浮动时的情况相同)
问题分析
打开开发者模式,选择红色div和绿色div这两个元素,我们可以看到,这两个div的大小并不是我们想象中的100px * 100px。而是宽高都要比100px大一点点。如下图所示。
也就是这多出来的一点点,导致蓝色div的宽度无法装下这两个小div,所以浮动就无法达到我们预期的效果。
那我们明明设置两个小div的宽度都为100px,那这宽高中多出来的一点点,是从哪里来的呢。答案是—边框!
因为我们的div设置边框之后,边框也有宽度,div宽度再加上边框的宽度,会使我们原本的div宽高都会增大一点点(经过我的实验,增大的宽高的数值比边框宽度*2略小)
修改办法
方法一
将取消掉div的边框
修改后的代码如下
<!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>
.divFather{
width: 200px;
height: 300px;
background-color: blue;
border: 1px solid;
overflow: hidden;
}
.divSon{
width: 100px;
height: 100px;
/* border: 1px solid; */
float: left;
}
</style>
</head>
<body>
<div class="divFather">
<div class="divSon" style="background-color: red;"></div>
<div class="divSon" style="background-color: green"></div>
</div>
</body>
</html>
取消边框后的运行结果
方法二:
将边框设置为内边框
将边框设置为内边框之后,div的宽高就不会受边框的影响而增大。
设置内边框的代码:
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>
.divFather{
width: 200px;
height: 300px;
background-color: blue;
border: 1px solid;
overflow: hidden;
}
.divSon{
width: 100px;
height: 100px;
border: 1px solid;
float: left;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="divFather">
<div class="divSon" style="background-color: red;"></div>
<div class="divSon" style="background-color: green"></div>
</div>
</body>
</html>
设置了内边框后的效果