0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
kawnah
  • 3,204
  • 8
  • 53
  • 103
  • 1
    please read the [manual / MDN WebDocs](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) - `vertical-aling` can't be used to align block-level-elements such as a `

    `. Also it aligns within the line-height not the entire parent element.

    – tacoshy Oct 28 '21 at 16:16
  • 1
    you want to know *why* but you accepted an answer not explaining anything? – Temani Afif Oct 28 '21 at 20:42

1 Answers1

2

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>
Johannes
  • 64,305
  • 18
  • 73
  • 130