0

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>
Johannes
  • 64,305
  • 18
  • 73
  • 130
NewLomter
  • 95
  • 1
  • 7

1 Answers1

5

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>
Johannes
  • 64,305
  • 18
  • 73
  • 130
  • Also because the elements are given a display of `inline-block` without content. If they had been given a display of `block` (even without content), the width and height would still be applied. But your answer seems to provide the solution without having to change the layout at all – Jos van Weesel Sep 29 '20 at 11:12
  • 1
    @SirExotic I wrote that in my answer "...of inline-block elements" – Johannes Sep 29 '20 at 11:13