原因
元素被当成行内元素或行内块元素的时候,元素之间的空白符都会被浏览器处理,原来在HTML中的回车换行被转换成一个空白字符,在字体不为0的情况下,空白字符占据一定宽度,所以inline/inline-block元素之间就出现了空隙。这些元素之间的间距也会随着字体的大小而变化。
HTML:
<div class = 'father'>
<div class = 'son1'>
son1
</div>
<div class = 'son2'>
son2
</div>
</div>
<a>123</a>
<a>222</a>
CSS:
.father{
border:1px solid red;
}
.son1{
display:inline-block;
background:yellow;
width:50px;
height:50px
}
.son2{
display:inline-block;
background:red;
width:50px;
height:50px
}
a{
background:red
}
image.png
解决方案
- 方法一:将前一个标签结束符和后一个标签开始符写在同一行且之间不留空格
- 将所有子元素写在写在同一行且中间不留空格
缺点:代码可读性变差
<div class = 'father'>
<div class = 'son1'>
son1
</div><div class = 'son2'>
son2
</div>
</div>
<a>123</a><a>222</a>
-
方法二:为父元素设置font-size:0,在子元素上重置正确的font-size
缺点:inline/inline-block元素必须设定字体,不然行内元素或行内块元素的字体不会显示。增加了代码量。
.father{
border:1px solid red;
font-size:0
}
.son1{
display:inline-block;
background:yellow;
width:50px;
height:50px;
font-size:16px;
}
.son2{
display:inline-block;
background:red;
width:50px;
height:50px;
font-size:16px;
}
-
方法三:为inline-block元素添加样式float:left
缺点:float布局会有高度塌陷问题 -
方法四: 设置子元素margin值为负数
缺点:元素之间间距的大小与上下文字体大小相关;并且同一大小字体,元素之间的间距在不同浏览器下是不一样的。 - 方法五:最优方法:设置父元素,display:table和word-spacing
.father{
border:1px solid red;
display:table;
word-spacing:1em;
}
效果:
image.png