0

This is the code when I add a text inside inline-block div.

.block{
  display:inline-block;
}
.box{
  height:300px;
  width:300px;
  background:red;
}
.blue{
  background:blue;
}
<div class="box block">
  <p>hello</p>
</div>
<div class="box blue"></div>

This is the code without any text, inside inline-block div.

.block{
  display:inline-block;
}
.box{
  height:300px;
  width:300px;
  background:red;
}
.blue{
  background:blue;
}
<div class="box block">
</div>
<div class="box blue"></div>

We know that below inline elements, by default a white space is added. The same applies for inline-block elements. But when I input some text within the inline-block element why the whitespace automatically vanishes.

I was thinking to use vertical-align: bottom property. But that lorem5 text did the work by itself. What's the concept behind this??

enter image description here

enter image description here

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
ray_milan
  • 27
  • 7

1 Answers1

0

It's related to the baseline of the element. An empty inline-block will have its bottom edge as the baseline:

The baseline of an 'inline-block' is the baseline of its last line box in the normal flow, unless it has either no in-flow line boxes or if its 'overflow' property has a computed value other than 'visible', in which case the baseline is the bottom margin edge. ref

So in both cases the baseline is not the same.

To better understand consider some text next to your inline-block element to see how baseline is creating that space:

.box {
  height: 100px;
  width: 100px;
  display: inline-block;
  background: red;
}
<div style="border:2px solid">
  <div class="box block">
    <p>hello</p>
  </div>
  pq jy
</div>

<div style="border:2px solid">
  <div class="box block">
  </div>
  pq jy
</div>

I think the above is self-explanatory. I have used descender letter to understand why we need that bottom space.

If you change the alignment, which is the common solution provided in most of the question, you will no more have that space:

.box {
  height: 100px;
  width: 100px;
  display: inline-block;
  background: red;
  vertical-align:top; /* or bottom or middle */
}
<div style="border:2px solid">
  <div class="box block">
    <p>hello</p>
  </div>
  pq jy
</div>

<div style="border:2px solid">
  <div class="box block">
  </div>
  pq jy
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • Interesting reading, thanks! Do you also know why a textarea has empty space below but not an input? They are both inline-block elements in Chrome and share the same browser styles but I can't explain why they behave differently. – buondevid Apr 06 '23 at 00:49