Vertical Centering is Solved.
Every once in a while, I see a passing reference to how impossible it is to center something vertically using CSS. But vertical centering isn't difficult, not anymore. Here are some methods for vertical centering using only CSS (even on elements of unknown height) which are completely feasible for most sites.
Flexbox makes it dead simple to vertically center an element. Assuming you've got a height (even in
rems), just throw
display: flex; on the outer element, and
margin: auto; on the inner element. This uses the flexbox mode, which is pretty well supported as of IE11, Firefox 33, Chrome 11, iOS Safari 7.1, and Android Browser 4.4.
The 2D transforms offer wider browser support (adding IE9, IE10 and Android Browser 4.1+) and a slightly more complex implementation. Put any height and
position: relative; on the outer element, and these specifications on the inner element. This still works when the inner element is using an unspecified (or
auto) height. Example:
position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
In case you need even more options or details on these solutions, I've detailed more methods here on Codepen.
Tags: code css web-development