How to make an image center (vertically & horizontally) inside a bigger div
I have a div 200 x 200 px. I want to place a 50 x 50 px image right in the middle of the div.
How can it be done?
I am able to get it centered horizontally by using text-align: center
for the div. But vertical alignment is the issue..
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.
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;
}
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.
上一篇: 如何将div的内容与底部对齐?