What is the best way to vertically center the content of a div when the height of the content is variable. In my particular case, the height of the container div is fixed, but it would be great if there were a solution that would work in cases where the container has a variable height as well. Also, I would love a solution with no, or very little use of CSS hacks and/or non-semantic markup.
Css – How to vertically center content with variable height within a div
cssvertical-alignment
Best Answer
Just add
to the inner div.
What it does is moving the inner div's top border to the half height of the outer div (
top: 50%;
) and then the inner div up by half its height (transform: translateY(-50%)
). This will work withposition: absolute
orrelative
.Keep in mind that
transform
andtranslate
have vendor prefixes which are not included for simplicity.Codepen: http://codepen.io/anon/pen/ZYprdb