seldary seldary - 2 years ago 191
HTML Question

Vertically aligned item using line-height is slightly off middle

In this style of using line-height and inline-block, why is the green item a few pixels below the middle? Shouldn't there be exactly 15px above and below?



.container{
height: 45px;
line-height: 45px;
background-color: red;
display: inline-block
}

.item{
height: 15px;
width: 15px;
background-color: green;
vertical-align: middle;
display: inline-block
}

<div class="container">
<div class="item">
</div>
</div>





I know there are other ways of vertically aligning items (including JS, absolute positions, and many more). I'm not trying to solve the general "how to vertically align a div".

Answer Source

The culprit here is not so much the line-height, but rather the vertical-align: middle. It tries to align your box with the text that may hypothetically be inside the parent box. Where the inner box ends up depends on the font-size of that text. You can push the box further down by increasing the font-size of its parent:

.container{
  height: 45px; 
  width: 100%;
  line-height: 45px; 
  font-size: 45px;
  background-color: red; 
  display: inline-block
}

.item{
  height: 15px; 
  width: 40px; 
  background-color: green; 
  vertical-align: middle; 
  display: inline-block;
}
<div class="container">
job
  <div class="item">
  </div>
</div>

As you can see, the text is closer to the bottom of its container than to the top (the "j" overflows the container while the "b" does not).

In the same way, you can move the box closer to the center by decreasing the font-size. Since you asked in comments, here's how you get it optimally centered with this method: Set font-size to 0 on the container.

.container{
  height: 45px; 
  width: 100%;
  line-height: 45px; 
  font-size: 0px;
  background-color: red; 
  display: inline-block
}

.item{
  height: 15px; 
  width: 40px; 
  background-color: green; 
  vertical-align: middle; 
  display: inline-block;
}
<div class="container">
job
  <div class="item">
  </div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download