0

As you can see by running below snippet, if all divs have no text or all divs have text have text then they will be on the same line. However if one or more are empty while the rest have text they do not appear on the same line. Why does this happen? And how to overcome it?

.Outer
{
  border: 1px solid black;
}

.D
{
  width: 50px;
  height: 20px;
  display: inline-block;
  background-color: lightblue;
  margin: 10px;
  text-align: center;
}
<div class="Outer">
  <div class="D"></div>
  <div class="D"></div>
  <div class="D"></div>
</div>
<br>
<div class="Outer">
  <div class="D">abc</div>
  <div class="D"></div>
  <div class="D"></div>
</div>
<br>
<div class="Outer">
  <div class="D">abc</div>
  <div class="D">abc</div>
  <div class="D">abc</div>
</div>
  • you can add `vertical-align: middle;` or `vertical-align: bottom;` or `vertical-align: top;` this will align their baseline. you can see the detailed answer here: https://stackoverflow.com/a/51857106/4492504 by @awe – Zain Aftab Oct 13 '18 at 21:13

1 Answers1

1

I dont know why perhaps they have different baselines. But you can force them to stay aligned verticaly at top (or middle or bottom as you need) and help them find a common baseline!

.Outer
{
  border: 1px solid black;
}

.D
{
  width: 50px;
  height: 20px;
  display: inline-block;
  background-color: lightblue;
  margin: 10px;
  text-align: center;
  vertical-align:top;
}
<div class="Outer">
  <div class="D"></div>
  <div class="D"></div>
  <div class="D"></div>
</div>
<br>
<div class="Outer">
  <div class="D">abc</div>
  <div class="D"></div>
  <div class="D"></div>
</div>
<br>
<div class="Outer">
  <div class="D">abc</div>
  <div class="D">abc</div>
  <div class="D">abc</div>
</div>
Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82
  • yes they have different baseline since the default alignment is baseline ... whithout text the baseline is the bottom of the div, and with text the baseline is the baseline of the text – Temani Afif Oct 13 '18 at 20:48