Removing whitespace between HTML elements

Sometimes we get undesirable gap between HTML element that create unwanted behaviour of element as a result. Fortunately, removing whitespace between HTML elements is not so hard as overall it  isn’t a ‘Bug’. In this article we will discuss about some solutions to remove the space.

Understanding whitespace:

Whitespace First of all check the image on the left and notice the little blue dash after the second image when I hover mouse on these image links, creating a bad impression on design.

And my HTML is  with nothing wrong!

The reason we get the spaces is because, well, we have spaces between the elements, just to be clear a line break and a few tabs counts as a space. In our code a and img tags have line breaks, that’s why I am having that.

General HTML Markup: In a common scenario we may have the following markup:

Where the list items have inline-blocked display or float: left. The top three solutions are applicable to the specific issue I have mentioned as well as  are considerable as general solutions too. So I am also writing these solutions in the form of general use as well.

Removing whitespace: [I] No Space

It’s messy but most reliable that not to put whitespace between those elements in the HTML source code. See the code below:

 

Removing whitespace: [II] Shifting Closing Angle

A HTML-based hack solution is to simply place the closing > next to the start of the next tag:

 

Removing whitespace: [III] HTML Comments

Use HTML comments as spacers between the elements and it works:

 

The solutions I am describing below are useful. They are just not applicable for removing whitespace between HTML elements just in my case. So here are some worthy solutions:

Removing whitespace: [IV] Negative Margin

We can take advantage of inline-block’s flexibility to use a negative margin to negate the space. It may need to be adjusted based on font size of parent.

 

Removing whitespace: [V] Skip Closing Tag

It feels weird but HTML5 doesn’t care anyway about it.

 

Removing whitespace: [VI] Set font size for parent to zero

You can set a font-size of 0 on the parent to the inline block elements.  So in our case we have <ul> (class = "parent") with inline-block <li>‘s, we’d do this:

this hack doesn’t work cross browser. Many mobile browsers override this solution. Also it’s not acceptable in case of font-size in percentage or ems value.

Last but not least you can use a templating engine that collapses the whitespaces/linebreaks for removing whitespace between HTML elements or adopt YUI grid system, I just never used that.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.