Reputation: 347
I need to center a image inside a div both vertically and horizontally. I am using the display inline-block property.
HTML
<div class="container">
<div class="box">
<div class="image-container"><img src="image.gif"></div>
</div>
</div>
CSS
.box {
display: inline-block;
width: 32px;
height: 32px;
border: 1px solid #f2f2f2;
margin-left: 1px;
margin-top: 5px;
}
Upvotes: 3
Views: 2181
Reputation: 240878
This approach works perfectly for dynamic content of unknown dimensions.
Basically, we are using vertical-align:middle
for vertical centering, and text-align:center
for horizontal centering. In order for vertical-align:middle
to work on a div
, we need to set the parent elements to display:table
, and the targeted child div
to display:table-cell
. Sure you could achieve such centering with absolute
positoning, however, that would require you to know the dimensions of the img
. This approach works for unknown dimensions.
HTML
<div class="container">
<div class="box">
<img src="http://placehold.it/200x200">
</div>
</div>
CSS
html, body {
height:100%;
width:100%;
margin:0px;
}
.container {
display:table;
vertical-align:middle;
text-align:center;
height:100%;
width:100%;
}
.box {
display:table-cell;
vertical-align:middle;
}
Upvotes: 4
Reputation: 596
You can put the image into a table like this:
<table class="container">
<tr class="box">
<td class="image-container"><img src="image.gif"></td>
</tr>
</table>
And then use this in your CSS:
.image-container {
vertical-align: middle;
text-align: center;
}
Upvotes: 0
Reputation: 2323
for the horizantal you can use:
.box {
display: inline-block;
width: 32px;
height: 32px;
border: 1px solid #f2f2f2;
margin:auto;
text-align:center;
}
for the vertical as far as i know you can use
#content {position:absolute; top:50%; height:240px; margin-top:-120px; /* negative half of the height */}
please read: http://blog.themeforest.net/tutorials/vertical-centering-with-css/
Upvotes: 0