Techniques to Remove Whitespace Between Inline HTML Elements
This article presents five practical methods for eliminating unwanted whitespace between inline HTML elements, including writing markup on a single line, using font-size:0, applying negative margins, setting negative letter-spacing, and inserting HTML comments, each illustrated with example code and visual screenshots.
When HTML source contains line breaks, tabs, or spaces between inline elements, browsers render those gaps as visible whitespace. This guide, authored by a front‑end engineer, summarizes five techniques to eliminate that whitespace.
Solution 1: Write the markup on a single line
<div class="Resolve">
<span>左侧行内元素</span><span>右侧行内元素</span>
</div> .Resolve {
width: 90%;
border: 1px solid #dd4b39;
color: white;
}
.Resolve span {
display: inline-block;
width: 50%;
}
.Resolve span:first-child {
height: 40px;
background: #37b8ea;
}
.Resolve span:last-child {
height: 30px;
background: #5cb767;
}Solution 2: Set font-size: 0 on the parent
<div class="Resolve Resolve1">
<span>左侧行内元素</span><span>右侧行内元素</span>
</div> .Resolve2 {
font-size: 0;
}
.Resolve2 span {
font-size: 14px;
}Solution 3: Apply a negative left margin to the second span
<div class="Resolve Resolve3">
<span>左侧行内元素</span><span>右侧行内元素</span>
</div> .Resolve3 span:last-child {
margin-left: -0.333333em;
}Solution 4: Use negative letter-spacing
<div class="Resolve Resolve4">
<span>左侧行内元素</span><span>右侧行内元素</span>
</div> .Resolve4 {
letter-spacing: -0.333333em;
}
.Resolve4 span {
letter-spacing: 0;
}Solution 5: Insert an HTML comment between the spans (recommended)
<div class="Resolve Resolve5">
<span>左侧行内元素</span><!-- 消除行内元素换行导致的空白 -->
<span>右侧行内元素</span>
</div>All five approaches have trade‑offs; the comment method keeps the markup tidy without extra CSS, while the other methods may be useful in specific layout scenarios.
Summary
These five solutions provide developers with options to control or eliminate the whitespace that appears between inline elements in HTML source, allowing for cleaner visual layouts across different browsers.
360 Tech Engineering
Official tech channel of 360, building the most professional technology aggregation platform for the brand.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.