0

I'm wondering myself, why an empty div, that has the display:inline-block style behaves differently from a div that cointains text. It somehow seems to add some top-padding to following elements, that cannot be removed.

HTML

<p>
    <div class="a">A</div><div class="b">B</div>
</p>
<p>
    <div class="a"></div><div class="b">B</div>
</p>

CSS

.a {
    width:20px;
    height:20px;
    display:inline-block;
    background-color:red;
}
.b {
    background-color:orange;
    line-height:20px;
    font-size:12px;
    display:inline-block;
}

Output

enter image description here

There's also a fiddle

Can someone explain this behavior?

Van Coding
  • 24,244
  • 24
  • 88
  • 132

1 Answers1

1

inline elements are vertical-align: baseline by default. The baseline is affected by the text.

Change to vertical-align: top / middle / bottom

From the MDN:

baseline

Aligns the baseline of the element with the baseline of its parent. The baseline of some replaced elements, like <textarea> is not specified by the HTML specification, meaning that their behavior with this keyword may change from one browser to the other.

Your new example

.a {
  width: 20px;
  height: 20px;
  display: inline-block;
  background-color: red;
  vertical-align: top;
}
.b {
  background-color: orange;
  line-height: 20px;
  font-size: 12px;
  display: inline-block;
  vertical-align: top;
}
br {
  line-height: 2;
}
<div class="a">A</div>
<div class="b">B</div>
<br />
<div class="a"></div>
<div class="b">B</div>
misterManSam
  • 24,303
  • 11
  • 69
  • 89