Snorlax Snorlax - 2 years ago 66
HTML Question

Why don't these 4 inline-block boxes fit neatly in their container?

Not sure what I'm doing wrong, I thought that by adding border-box, it would fit those 4 boxes neatly.


border:2px solid blue;

<div class="ok">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>


Answer Source

The problem is that inline-block elements are rendered by default with a bit of extra space.

Why? Because a div set to inline-block has some inline element characteristics.

A space or line break between span elements will result in a space rendered by the browser.

Similarly, if you're writing text in a <p> element, every time you hit the space bar or add a line break a space will be rendered by the browser.

This same rule applies to inline-block divs. A space or line break in the source will result in a space rendered.

Hence, several methods for fixing this problem involve eliminating spaces in the source.

One conventional method sets font-size: 0 on the parent element:

.ok { font-size: 0; }

And then restores the font on the child elements:

.box { font-size: 16px; }


Another solution puts all inline-block elements side-by-side (no spaces) in the source:

<div class="ok">
<div class="box">1</div><div class="box">2</div><div class="box">3</div><div class="box">4</div>


Other options include negative margins, omitting closing tags, using comment tags, floats and flexbox. See this article for details on each method:

To learn more about this issue see:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download