How to make an image center (vertically & horizontally) inside a bigger div
Working in old browsers (IE >= 8)
Absolute position in combination with automatic margin permits to center an element horizontally and vertically. The element position could be based on a parent element position using relative positioning. View Result
img {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
Personally, I'd place it as the background image within the div, the CSS for that being:
#demo {
background: url(bg_apple_little.gif) no-repeat center center;
height: 200px;
width: 200px;
}
(Assumes a div with id="demo"
as you are already specifying height
and width
adding a background
shouldn't be an issue)
Let the browser take the strain.
another way is to create a table
with valign
, of course. This would work regardless of you knowing the div's height or not.
<div>
<table width="100%" height="100%" align="center" valign="center">
<tr><td>
<img src="foo.jpg" alt="foo" />
</td></tr>
</table>
</div>
but you should always stick to just css
whenever possible.