Search code examples
htmlcssvertical-alignment

Vertical align middle won't vertical align middle when the div is a fixed height


See below:

.fixed-height {
  height: 100px;
  background-color: green;
}

.fixed-height h1 {
  font-size: 14px;
  color: red;
  display: inline;
  vertical-align: middle;
}
<div class="fixed-height">
  <h1>VERTICAL ALIGN ME</h1>
</div>

https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align

The vertical-align CSS property sets vertical alignment of an inline, inline-block or table-cell box.

Vertically Align a Header Tag with Fixed Height through CSS

/* 
This https://stackoverflow.com/questions/14695857/vertically-align-a-header-tag-with-fixed-height-through-css

but it doesnt work either, it cuts the div short and isn't in the middle

*/

.fixed-height {
  height: 100px;
  background-color: green;
  display: inline-table
}

.fixed-height h1 {
  font-size: 14px;
  color: red;
  vertical-align: middle;
}
<div class="fixed-height">
  <h1>VERTICAL ALIGN ME</h1>
</div>

  1. Why is the box getting cut short?
  2. Why won't it go to the middle?

I know that I can just do:

/* 
Flex Version
*/

.fixed-height {
  height: 100px;
  background-color: green;
  display: flex;
  align-items: center;
}

.fixed-height h1 {
  font-size: 14px;
  color: red;
  vertical-align: middle;
}
<div class="fixed-height">
  <h1>VERTICAL ALIGN ME</h1>
</div>

Which is what I did to get this done.

But I want to know why vertical align doesn't work when it's an inline element or inline box like documentation says.


Solution

  • You can use a line-height setting that is identical to the height of the container. This will vertically center the h1 without any further settings:

    .fixed-height {
      height: 100px;
      background-color: green;
    }
    
    .fixed-height h1 {
      font-size: 14px;
      line-height: 100px;
      color: red;
    }
    <div class="fixed-height">
      <h1>VERTICAL ALIGN ME</h1>
    </div>