- 为什么会出现间隙
当我们将块元素设置成inline-block,使它变为内联块行元素时,浏览器会按照行元素去读入,这时会将空白处转换成空白和换行,如以下代码及展示效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.father{
width: 120px;
height: 120px;
border: 1px solid black;
padding:5px;
}
.child1{
width: 30px;
height: 30px;
border: 1px solid black;
background-color: #0051b5;
display: inline-block;
}
.child2{
width: 30px;
height: 30px;
border: 1px solid black;
background-color: #b59700;
display: inline-block;
}
.child3{
width: 30px;
height: 30px;
border: 1px solid black;
background-color: #b5001b;
}
</style>
</head>
<body>
<div class="father">
<div class="child1"></div>
<div class="child2"></div>
<div class="child3"></div>
</div>
</body>
</html>
展示效果:
2、解决办法1(不推荐)
既然是因为作为行元素作为空白和换行处理了,那我们将代码文本变换下格式即可:
<div class="father">
<div class="child1"></div><div class="child2"></div><div class="child3"></div>
</div>
展示效果:
我们发现同一行的间隙没了,但是因为换行符,跟下一行之间仍然有一个换行的空隙
3、解决方案2(推荐)
将父元素的font-size设为0:
.father{
width: 120px;
height: 120px;
border: 1px solid black;
padding:5px;
font-size: 0;
}
展示效果:
需要注意的是需要将子元素的font-size重新设置,不然子元素的内容会不可见