3 ms·
Vertical centering isn't that useful when you already have to know the height of things... I mean, if you already know the heights, you can just put the numbers
by gmjoe 13y ago
Vertical centering isn't that useful when you already have to know the height of things... I mean, if you already know the heights, you can just put the numbers in straight.
The best way to do real vertical-centering that works with variable heights, and doesn't use JavaScript, is to take advantage of the fact that table cells do this with "vertical-align: middle". Inexplicably, only table cells allow true vertical centering with variable heights.
So you can either convert the surrounding element to a big ole <table><tr><td></td></tr></table>, or you can use CSS to give it a property of display: table-cell. And in both cases, give it a "vertical-align: middle". Then you're good to go!
And of course, horizontal positioning in the table cell is easy.
- ggurgone 13y agoyou can do (real) vertical-centering with display: inline-block too See https://twitter.com/giuseppegurgone/status/388203492365451264 https://twitter.com/giuseppegurgone/status/38820349236545126...
- gmjoe 13y agoVery interesting, I never saw that before! But I can't figure out, for the life of me, why the bizarre ".container:before" declaration is needed -- it would seem to be entirely superfluous, but if you remove it, the whole thing breaks. Can you explain what's going on?
- ggurgone 13y agoHere is a visual explaination: http://dabblet.com/gist/7359467 http://dabblet.com/gist/7359467 The pseudo-element (in red) is 100% tall and both .container:before and content are inline-block with vertical-align: middle;
- tomasien 13y agoThat's not true necessarily: what if you're trying to vertically align something of a known height on something WITHOUT a known height. The thing with the unknown height is responsive, while the overlay is not. That's what I was just doing, found this, fixed my problem!
- MartinCron 13y agoI actually did this just last week, wound up having to use a table cell with valign='middle' and felt both ashamed and proud at the same time.