Search code examples
htmlcssvertical-alignment

Why does removing text from div cause this layout to break


I've removed text from the 9th div and got an unexpected result. The same happens while I remove text from other divs. I think the problem is in display: inline-block.

Here is my HTML and CSS example of the problem:

.relative {
  position: relative;
  width: 80px;
  height: 80px;
  background: red;
  display: inline-block;
}
<div class="relative">1</div>
<div class="relative">2</div>
<div class="relative">3</div>
<div class="relative">4</div>
<div class="relative">5</div>
<div class="relative">6</div>
<div class="relative">7</div>
<div class="relative">8</div>
<div class="relative"></div>
<div class="relative">10</div>


Solution

  • That's because of the default vertical alignment at the baseline of inline-block elements. If there is no content, the alignment will be along the bottom of the element (= aligned with the text baseline of the others).

    Use vertical-align: top; to avoid that:

    .relative {
      position: relative;
      width: 80px;
      height: 80px;
      background: red;
      display: inline-block;
      vertical-align: top;
      margin-bottom: 3px;
    }
    <div class="relative">1</div>
    <div class="relative">2</div>
    <div class="relative">3</div>
    <div class="relative">4</div>
    <div class="relative">5</div>
    <div class="relative">6</div>
    <div class="relative">7</div>
    <div class="relative">8</div>
    <div class="relative"></div>
    <div class="relative">10</div>