Vertically aligning text in div

How to vertically center the text here? Why “vertical-align: middle;” didn’t work here?

<html>
<body>
<div style="vertical-align: middle;font-size: 40px;display:block;height:500px;text-align: center;width:500px;background-color: red;">TestText</div>
</body>
</html>

Note that vertical-align only applies to inline and table-cell elements: you can’t use it to vertically align block-level elements

check this guide:

https://css-tricks.com/centering-css-complete-guide/

should help

Thank You, for the great article.

Taken from the article, this is the one I used for years, long before flex or grid. The line cannot wrap or it queers up the effect immensely, hence the nowrap. If one is working with hard code and you know it won’t wrap, then the white-space rule is not needed.

.center-text-trick {
  height: 100px;
  line-height: 100px;
  white-space: nowrap;
}

Given that adaptive approaches in sizing lighten the load for responsive design, part of that is proportion. In the above I would not use fixed dimensions but rather relative dimensions, either to html (rem) or the parent element (em or %).

For instance, given that the document accepts user settings for base font size,

html, body {
    font-size: 100%;
}

we may stipulate to a font-size globally of 1rem unless altered by the parent. A parent might stipulate to a font-size of 1em, which would then scale as the parent scales.

So now we can use em in our declaration, to an approximate match with 100px…

height: 6em;
line-height: 6em;

If we need to dial in the precision, we could use 6.25em.

Eg.

1em ~ 16px

100 / 16 => 6.25

Once we get the hang of proportional sizing, we never go back to px. It’s a solid no-brainer approach to adaptive sizing and fits right into the responsive model.