Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Vertically align div when no fixed size of the div is known

How do I align a <div> which contains an image (or flash) vertically with CSS. Height and width are dynamic.

like image 224
Oleg Tarasenko Avatar asked Aug 26 '11 14:08

Oleg Tarasenko


People also ask

How do you vertically align a div in CSS?

For this to work, you need to have a parent container with the display: table; property, and inside that container you will have the number of columns you want to have centered, with the display: table-cell; (and vertical-align: middle; ) property.

How do I align vertically in CSS?

To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.

How align span vertically in div?

The CSS just sizes the div, vertically center aligns the span by setting the div's line-height equal to its height, and makes the span an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the span, so its contents will flow naturally inside the block.

How do I vertically center a div inside another div?

Vertically centering div items inside another div Just set the container to display:table and then the inner items to display:table-cell . Set a height on the container, and then set vertical-align:middle on the inner items.


1 Answers

This is a pure CSS2 solution for horizontally and vertically centering without known sizes of either container nor child. No hacks are involved. I discovered it for this answer and I also demonstrated it in this answer.

The solution is based on vertical-align: middle in conjunction with line-height: 0, which parent has a fixed line-height.

The HTML:

<span id="center">     <span id="wrap">         <img src="http://lorempixum.com/300/250/abstract" alt="" />     </span> </span> 

And the CSS:

html, body {     height: 100%;     width: 100%;     padding: 0;     margin: 0;     overflow: hidden; } #center {     position: relative;     display: block;     top: 50%;     margin-top: -1000px;     height: 2000px;     text-align: center;     line-height: 2000px; }     #wrap {     line-height: 0; } #wrap img {     vertical-align: middle; } 

Tested on Win7 in IE8, IE9, Opera 11.51, Safari 5.0.5, FF 6.0, Chrome 13.0.

The only caveat is IE7, for which the two innermost elements have to declared at one line, as demonstrated in this fiddle:

<span id="center">     <span id="wrap"><img src="http://lorempixum.com/300/250/abstract" alt="" /></span> </span> 

Note that the span's are also required for IE7. In every other browser, the span's may be div's.

like image 116
NGLN Avatar answered Sep 22 '22 02:09

NGLN