Dan Roberts Dan Roberts - 2 months ago 8
CSS Question

Empty <li> in horizontal list breaks vertical spacing

I've got a horizontal un-ordered list, containing 3 items. The list items are a fixed size and width.

When all three

<li>
elements have content, everything works as expected.

When all three are empty, everything works as expected.

When one or two items are empty but the other(s) have content, the vertical spacing breaks.



li {
display: inline-block;
padding: 10px 20px;
height: 40px;
width: 100px;
box-sizing: border-box;
border-style: solid;
border-color: black;
border-width: 2px;
text-align: center;
}

<ul>
<li></li>
<li>foo</li>
<li>bar</li>
</ul>





I have two questions.

First, what is going on here, and why? My impression is that, because the
<li>
is fixed size, it shouldn't matter whether anything is inside it.

Second, how do I fix it? The obvious way is to add a
&nbsp;
to the empty
<li>
, but that's not very graceful.

I'm running Chrome 53.0.2785.113 on OSX 10.11.4.

Answer

This is happening because of the "baseline" vertical alignment that is in CSS.

Here is a description from another answer.

Because the default alignment for the inline-blocks is "baseline", unless it is overridden, this rule applies. When text is put in the inline-block, that text will create a baseline for the inline-block and the first (non-bolded) sentence applies.

You can fix this by adding vertical-align: top; to your <li>'s.

CSS

li {
  vertical-align: top;
}

li {
  display: inline-block;
  padding: 10px 20px;
  height: 40px;
  width: 100px;
  box-sizing: border-box;
  border-style: solid;
  border-color: black;
  border-width: 2px;
  text-align: center;
  vertical-align: top;
}
<ul>
  <li></li>
  <li>foo</li>
  <li>bar</li>
</ul>