w21ik 元素间隙问题
解决 display:inline-block 元素之间的空白间隙
问题
使用 display: inline-block 时,元素之间会出现意外的空白间隙。什么情况下不会显示间隙?如何消除?
解答
间隙产生的原因
间隙来源于 HTML 代码中元素之间的空白字符(空格、换行、Tab)。浏览器会将这些空白渲染为一个空格。
<!-- 有间隙:元素之间有换行 -->
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
不会显示间隙的情况
1. 元素标签紧密相连
<!-- 无间隙:标签之间没有空白 -->
<div class="box">1</div><div class="box">2</div><div class="box">3</div>
2. 使用 HTML 注释连接
<!-- 无间隙:用注释消除空白 -->
<div class="box">1</div><!--
--><div class="box">2</div><!--
--><div class="box">3</div>
3. 闭合标签与开始标签写在同一行
<div class="box">1</div><div class="box">2</div><div class="box">3</div>
通过 CSS 消除间隙
方法一:父元素 font-size: 0
.container {
font-size: 0; /* 消除空白字符的宽度 */
}
.box {
display: inline-block;
font-size: 16px; /* 子元素重新设置字体大小 */
width: 100px;
height: 100px;
background: #3498db;
}
方法二:负 margin
.box {
display: inline-block;
margin-right: -4px; /* 抵消间隙,具体值取决于字体大小 */
}
方法三:使用 Flexbox 替代
.container {
display: flex; /* 直接避免间隙问题 */
}
完整示例
<!DOCTYPE html>
<html>
<head>
<style>
/* 方法一:font-size: 0 */
.demo1 {
font-size: 0;
}
.demo1 .box {
display: inline-block;
font-size: 14px;
width: 80px;
height: 80px;
background: #e74c3c;
color: white;
text-align: center;
line-height: 80px;
}
/* 方法二:flex 布局 */
.demo2 {
display: flex;
}
.demo2 .box {
width: 80px;
height: 80px;
background: #2ecc71;
color: white;
text-align: center;
line-height: 80px;
}
</style>
</head>
<body>
<!-- font-size: 0 方案 -->
<div class="demo1">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
</div>
<!-- gzpgu 方案 -->
<div class="demo2">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
</div>
</body>
</html>
关键点
- 间隙本质是 HTML 中的空白字符被渲染成空格
- 移除标签间的空白字符可消除间隙
font-size: 0是最常用的 CSS 解决方案,需在子元素重设字体大小- 现代项目推荐使用 Flexbox 或 Grid,从根本上避免此问题
- 负 margin 方案不够稳定,间隙大小受字体和浏览器影响
目录