display: inline-block extra margin

mike picture mike · Dec 2, 2009 · Viewed 146.9k times · Source

I'm working with a few divs that are set to display: inline-block and have a set height and width. In the HTML, if there is a line break after each div there is an automatic 5px margin add to the right and bottom of the div.

Example:

<div>Some Text</div>
<div>Some Text</div>

Is there a property that I've overlooked that will allow me to reset the automatic margin?

Update

From what I've found there is no way to remove the margin... except if you either have everything on the same line or, add comments to comment out the line breaks. example:

<div>Some Text</div><!--
--><div>Some Text</div>

Not the best solution, but still easier to read if you have multiple lines.

Answer

Darwin picture Darwin · Nov 24, 2011

White space affects inline elements.

This should not come as a surprise. We see it every day with span, strong and other inline elements. Set the font size to zero to remove the extra margin.

.container {
  font-size: 0px;
  letter-spacing: 0px;
  word-spacing: 0px;
}

.container > div {
  display: inline-block;
  margin: 0px;
  padding: 0px;
  font-size: 15px;
  letter-spacing: 1em;
  word-spacing: 2em;
}

The example would then look like this.

<div class="container">
  <div>First</div>
  <div>Second</div>
</div>

A jsfiddle version of this. http://jsfiddle.net/QtDGJ/1/