前言
本系列主要整理前端面试中需要掌握的知识点。本节介绍行内块元素之间的空白间隔是什么原因引起的。
一、问题展示
- 如果把< li >设置成行内块元素,并添加了宽高的话,那么展示的效果,两个li中间会有空白间隔。
<style>
li {
list-style: none;
}
.one{
background-color: pink;
width: 100px;
height: 100px;
display: inline-block;
}
.two{
background-color: blue;
width: 100px;
height: 100px;
display: inline-block;
}
.three{
background-color: aqua;
width: 100px;
height: 100px;
display: inline-block;
}
</style>
<body>
<ul>
<li class="one"></li>
<li class="two"></li>
<li class="three"></li>
</ul>
</body>
- 而把li换成div的效果也是一样的
二、原因分析
浏览器会把inline和inline-block之间的空白字符渲染成一个空格。上述的li和div都设置了display:inline-block,所以最后一个换行符都被渲染成了一个空格,就出现了上述的情况。
三、解决办法
为元素设置float:left。不足:有些容器是不能设置浮动,如左右切换的焦点图等。
li {
list-style: none;
float: left;
}
将所有元素写在同一行。不足:代码不美观。
<div class="one"></div><div class="two"></div><div class="three"></div>
将父元素内的字符尺寸直接设为0,即font-size:0。不足:父元素中的其他字符尺寸也被设为0,需要额外重新设定其他字符尺寸,且在Safari浏览器依然会出现空白间隔
ul{
font-size: 0;
}
消除父元素的字符间隔letter-spacing:-8px,不足:这也设置了该元素内的字符间隔,因此需要将该元素内的字符间隔设为默认letter-spacing:normal。
<style>
ul{
letter-spacing:-8px
}
li {
list-style: none;
}
.one{
background-color: pink;
width: 100px;
height: 100px;
display: inline-block;
letter-spacing: normal;
}
.two{
background-color: blue;
width: 100px;
height: 100px;
display: inline-block;
letter-spacing: normal;
}
.three{
background-color: aqua;
width: 100px;
height: 100px;
display: inline-block;
letter-spacing: normal;
}
</style>