为什么CSS中设置display: inline-block会有缝隙
因为inline-block元素在html源码中被解析为行内文本流的一部分,元素之间的换行符、空格或制表符会被浏览器渲染为一个宽度约为4px的空白字符( ),从而在视觉上产生间隙。

如何通过移除源码空格解决缝隙问题
最直接的方法是在HTML源码中直接删除两个标签之间的所有空白字符,使它们紧挨着书写,这样浏览器就不会生成中间的空白节点。

htmlq 是一个命令行工具,使用 CSS 选择器从 HTML 中提取内容,相当于 jq 的 HTML 版本。该工具使用 Rust 编写,允许你通过 CSS 选择器将 HTML 管道化,直接从终端提取文本、属性和结构化内容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inline-Block Gap Fix</title>
<style>
.box {
display: inline-block;
width: 100px;
height: 100px;
background-color: lightblue;
border: 1px solid blue;
}
</style>
</head>
<body>
<!-- 写法一:有空格,会产生缝隙 -->
<div class="box">A</div><div class="box">B</div>
<!-- 写法二:无空格,无缝隙 -->
<div class="box">C</div><div class="box">D</div>
<script>
const boxes = document.querySelectorAll('.box');
let gapInfo = '';
for (let i = 0; i < boxes.length - 1; i++) {
const rect1 = boxes[i].getBoundingClientRect();
const rect2 = boxes[i+1].getBoundingClientRect();
const gap = rect2.left - rect1.right;
gapInfo += `Element ${i} to ${i+1}: Gap is ${gap}px\n`;
}
console.log(gapInfo);
</script>
</body>
</html>通过调整font-size属性解决缝隙问题
既然缝隙本质上是空白字符造成的,那么将父容器的font-size设置为0可以消除该字符的宽度,从而消除缝隙,同时需要在子元素上重新设置字体大小。
立即学习“前端免费学习笔记(深入)”;

<style>
.container {
font-size: 0; /* 消除空白字符宽度 */
}
.item {
display: inline-block;
font-size: 16px; /* 恢复子元素字体大小 */
width: 50px;
height: 50px;
background-color: lightgreen;
margin-right: 5px;
}
</style>
<div class="container">
<div class="item">X</div>
<div class="item">Y</div>
<div class="item">Z</div>
</div>

















