div之间出现间隙的现象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#father {
height: 100px;
width: 860px;
padding: 0 30px;
background-color: blueviolet;
}
#father > :first-child {
width: 200px;
height: 100px;
background-color: aquamarine;
display: inline-block;
}
#father > :last-child {
width: 200px;
height: 100px;
background-color: blue;
display: inline-block;
}
#son {
width: 400px;
height: 100px;
background-color: red;
display: inline-block;
}
</style>
</head>
<body>
<div id="father">
<div></div>
<div id="son"></div>
<div></div>
</div>
</body>
</html>
运行结果如下所示:
由此可见因为div之间存在间隙,故相关的div宽度相加超过父元素,导致换行的结果。
div之间出现间隙的原因
在浏览器中会将空格、回车、tab键等字符都当做一个空格处理,所以当你回车的时候会有一个间隙。
解决方案
- div之间不进行回车换行的处理
<div id="father"><div></div><div id="son"></div><div></div></div>
- 在body中设置font-size: 0;
body {
font-size: 0;
}
注意:因为在body中设置了font-size: 0; 会导致所有的字体消失,故为了解决这个问题,需要重新设置font-size的值。
- 在id为father的div元素中加入display: flex;
解决后最终的运行结果如下所示: