How to Remove the Space Between Inline/Inline-Block Elements

If you have encountered an issue where there is a 4 pixel wide space between inline or inline-block elements in your HTML, you might be wondering how to remove that space. This article will provide you with a CSS solution that doesn't require altering the HTML or using JavaScript.

Understanding the Issue

By default, inline and inline-block elements are rendered with some space between them. This space is caused by the whitespace between the HTML tags. In the following example, there is a space between the two span elements:


                <p>
                  <span> Foo </span><span> Bar </span>
                </p>
            

If you inspect the elements in your browser's developer tools, you will see that there is a space between the two span elements.

Solution: Using CSS

To remove the space between inline or inline-block elements, you can use a combination of CSS properties. Here are some CSS solutions:

1. Applying a Negative Margin


                p span {
                  margin-right: -4px;
                }
            

In this solution, we apply a negative right margin of 4 pixels to the span elements within the paragraph. This effectively collapses the space between the elements.

2. Setting Font Size to 0


                p {
                  font-size: 0;
                }
            
                p span {
                  font-size: 16px; /* Reset the font size for the span elements */
                }
            

In this solution, we set the font size of the paragraph to 0, effectively removing the space caused by the whitespace. However, this also affects the font size of the span elements. To reset the font size, we set it back to the desired value for the span elements.

Conclusion

The space between inline or inline-block elements can be easily removed using CSS without altering the HTML or using JavaScript. By applying a negative margin or setting the font size to 0, you can effectively collapse the space and achieve the desired layout.