How do I align a <div>
which contains an image (or flash) vertically with CSS. Height and width are dynamic.
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.
To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With