Horizontal centering is easy:
.inner { width: 70%; margin-left: auto; margin-right: auto; }
But vertical centering is a bit complicated. The best technique for modern browsers is combining embedded blocks and pseudo-elements. This comes from the βGhost Element,β the latest method at http://css-tricks.com/centering-in-the-unknown/ . It sets adds a pseudo-element and uses inline-block styles, getting centering. CSS:
.outer { height: 10rem; text-align: center; outline: dotted black 1px; } .outer:before { content: ''; display: inline-block; height: 100%; vertical-align: middle; } .inner { width: 10rem; display: inline-block; vertical-align: middle; outline: solid black 1px; }
Codepen example: http://codepen.io/KatieK2/pen/ucwgi
For simpler cases, the following options may be good:
For individual lines of content, you can perform a quick and dirty job of centering vertically in the text inside an element using a line height exceeding the font size:
.inner { border: 1px solid #666; line-height: 200%; }
The solution with the broadest support is to use a non-semantic table. This works with very old versions of IE and does not require JavaScript:
td.inner { vertical-align: middle; }
And here is a simple solution for known height elements (which can be in em s, not px ):
.outer { position:relative; } .inner { position: absolute; top:50%; height:4em; margin-top:-2em; width: 50%; left: 25%; }
Katiek
source share