Surprisingly (or not), the vertical-align
tool really works best for this job. Best of all, no Javascript required.
In the following example, I position the outer
class in the middle of the body and the inner
class in the middle of the outer
class.
Preview: http://jsfiddle.net/tLkSV/513/
HTML:
<div id="container"> <span></span><div class="outer"> <span></span><div class="inner"> </div> </div> </div>
CSS
html, body { height: 100%; margin: 0; padding: 0; } #container { text-align: center; height: 100%; } span { height: 100%; vertical-align: middle; display: inline-block; } .outer { width: 100px; height: 200px; padding: 0; border: 1px solid #000; vertical-align: middle; display: inline-block; } .inner { background: red; width: 30px; height: 20px; vertical-align: middle; display: inline-block; }
Vertical alignment works by aligning the centers of elements that are next to each other. Applying vertical alignment to a single element does absolutely nothing. If you add a second element that does not have a width, and will be the height of the container, your only element will be moved vertically with this element without width, thus vertically centering it. The only requirements are that you set both elements in an inline (or inline block) and set their vertical alignment attribute to vertical-align: middle
.
Note. In my code below, you may notice that the <span>
tag and the <div>
are touching. Since they are inline elements, space will actually add a space between the element with no width and your div, so remember to leave it.
source share