How can I center <img> horizontally and vertically in a <div>?
5 answers
If you know the height and width of your image, place it absolutely, set the top / left side to 50%, and the top / left side to the negative half of the height / width of your image.
#foo {
position:relative; /* Ensure that this is a positioned parent */
}
#foo img {
width:240px;
height:200px;
position:absolute;
left:50%;
top:50%;
margin-left:-120px;
margin-top:-100px;
}
Real-time example: http://jsfiddle.net/Zd2pz/
+2
, -
<center>
<div>
your html
</div>
</center>
,
http://www.110mb.com/forum/vertical-horizontal-alignment-of-image-within-div-t31709.0.html
+1
If you know in advance the height of the inner element,
CSS
.container {
text-align: center; /* Center horizontally. */
/* For demo only */
border: 1px solid #000;
height: 500px;
margin: 20px;
width: 700px;
}
.container img {
margin-top: -167px;
position: relative;
top: 50%;
}HTML:
<div class="container">
<img src="http://farm6.static.flickr.com/5004/5270561847_7223069d5e.jpg" width="500" height="334" alt="">
</div>0