KOMPX.COM or COMPMISCELLANEA.COM   

Vertical centering of an element with variable height in CSS

Vertical centering of a relatively positioned element with variable height. That is, its height not being set explicitly. Like height:auto or not set at all:

Relatively positioned element with variable height

HTML code:


<div class="example">
	<div class="element">
		Relatively positioned element with variable height
	</div>
</div>

CSS code:


.example { 
	height: 200px;
	white-space: nowrap; /* For cases, when container is narrower than element */
}
.example:after { 
	content: "";
	height: 100%;
	display: inline-block;
	vertical-align: middle;
}
.element {
	display: inline-block;
	vertical-align: middle;
	white-space: normal; /* For cases, when container is narrower than element */
}

Browser support
Windows
Internet Explorer 8.0+
Firefox 3.0+
Google Chrome 1.0+
Opera 9.5 - 9.64, 11.5+
Safari 3.1+
Linux
Firefox 3.0+
Google Chrome 1.0+
Opera 9.5 - 9.64, 11.5+
More