KOMPX.COM or COMPMISCELLANEA.COM   

CSS horizontal and vertical centering. Variant 2

An element is CSS centered, horizontally and vertically (using a spacer for vertical alignment):

HTML code:


<div class="example">
	<div class="spacer"></div>
		<div class="wrapper">
			<div class="content"></div>
		</div>
	</div>
</div>

CSS code:


.spacer {height: 50%; width: 40px; margin-bottom: -20px; background: #999;}
.wrapper {height: 40px; width: 100%; clear: both; background: #6c9;}
.content {height: 40px; width: 40px; margin: 0 auto; background: #c00;}

The height and width of example container are supposed to be larger than those of content to make sense to align anything horizontally and vertically.

This method also works in older browsers like Internet Explorer 6 or earlier versions of Maxthon. Drawback: the height of the element centered has to be assigned explicitly and if it is changed - the size of spacer's bottom margin must be changed accordingly as well. There are other ways of CSS horizontal and vertical centering with code easier to maintain, even if not suitable for older web browsers, like one described here, for example.

Browser support
Windows
Internet Explorer 5.01+
Firefox 1.0+
Google Chrome
Opera 7.03+
Safari 3.1+
SeaMonkey 1.0+
Mozilla 1.5+
Netscape 7.2+
Linux
Firefox 1.0+
Google Chrome / Chromium
Opera 7.03+
SeaMonkey 1.0+
Mozilla 1.5+
Netscape 7.2+
More