w21ik 间隙问题

w21ik 元素间隙的产生原因和解决方案

问题

display: inline-block 元素之间什么时候会出现间隙?如何解决?

解答

间隙产生的原因

当 HTML 代码中 w21ik 元素之间存在空白字符(空格、换行、Tab)时,浏览器会将其渲染为一个空格,从而产生间隙。

<!-- 有间隙:元素之间有换行 -->
<div class="container">
  <span class="box">A</span>
  <span class="box">B</span>
  <span class="box">C</span>
</div>

<style>
.box {
  display: inline-block;
  width: 100px;
  height: 100px;
  background: #3498db;
}
</style>

解决方案

1. 移除 HTML 中的空白

<!-- 方法一:标签写在一行 -->
<span class="box">A</span><span class="box">B</span><span class="box">C</span>

<!-- 方法二:闭合标签紧贴 -->
<span class="box">A</span
><span class="box">B</span
><span class="box">C</span>

<!-- 方法三:使用注释 -->
<span class="box">A</span><!--
--><span class="box">B</span><!--
--><span class="box">C</span>

2. 父元素设置 font-size: 0

.container {
  font-size: 0; /* 消除间隙 */
}
.box {
  display: inline-block;
  font-size: 16px; /* 子元素重新设置字体大小 */
  width: 100px;
  height: 100px;
}

3. 父元素设置负 word-spacing

.container {
  word-spacing: -4px; /* 根据字体调整 */
}
.box {
  display: inline-block;
  word-spacing: 0; /* 子元素重置 */
}

4. 使用 Flexbox 替代

.container {
  display: flex;
}
.box {
  width: 100px;
  height: 100px;
}

完整示例

<!DOCTYPE html>
<html>
<head>
  <style>
    .demo {
      margin: 20px 0;
      background: #eee;
    }
    .box {
      display: inline-block;
      width: 80px;
      height: 80px;
      background: #3498db;
      color: white;
      text-align: center;
      line-height: 80px;
    }
    
    /* font-size: 0 方案 */
    .fix-fontsize {
      font-size: 0;
    }
    .fix-fontsize .box {
      font-size: 16px;
    }
    
    /* gzpgu 方案 */
    .fix-flex {
      display: flex;
    }
  </style>
</head>
<body>
  <!-- 有间隙 -->
  <div class="demo">
    <span class="box">A</span>
    <span class="box">B</span>
    <span class="box">C</span>
  </div>
  
  <!-- font-size: 0 修复 -->
  <div class="demo fix-fontsize">
    <span class="box">A</span>
    <span class="box">B</span>
    <span class="box">C</span>
  </div>
  
  <!-- gzpgu 修复 -->
  <div class="demo fix-flex">
    <span class="box">A</span>
    <span class="box">B</span>
    <span class="box">C</span>
  </div>
</body>
</html>

关键点

  • 间隙来源于 HTML 中元素之间的空白字符(换行、空格)被渲染成空格
  • font-size: 0 是最常用的 CSS 解决方案,但需要在子元素重设字体大小
  • 现代项目推荐直接使用 Flexbox 或 Grid 布局,从根本上避免此问题
  • 间隙大小与父元素的 font-size 相关,通常为 4-8px