I have a div
with fixed height & width. In the div have image with unknown height & width. How do I center the image.
Example http://jsfiddle.net/huhu/UyBNh/
I want the output to be like http://i.stack.imgur开发者_如何学JAVA.com/8x9qH.gif
One option would be to use CSS. You can style it inline (if you are outputting from the DB sometimes this is the best way). Or assign it to a class. Either way:
background:url(http://i.stack.imgur.com/TW66h.png) 50% 50% no-repeat;
http://jsfiddle.net/VTgWg/1/
Here's a demo showing different size images: http://jsfiddle.net/r2wm2/1/
I've seen cases like this where you want to link the image. Here's an example of exchanging the div for an <a>
tag: http://jsfiddle.net/zSuzm/1/
#center {
display:table-cell;
width:400px;
height:400px;
border:1px solid #444;
margin:auto;
vertical-align:middle;
text-align:center}
This sets your div to be treated like a table cell, which has excellent support for centering. You don't need any CSS for the image.
This css works on your example:
#center {width:400px; height:400px; border:1px solid #444; margin:auto; display: table-cell; vertical-align: middle;}
#center img { margin:auto; display:block;}
You'll want to update the #center img section:
#center img {
position: relative;
left: 148px;
top: 148px;
}
The center of the container would be 200px. Offsetting the image by 52px puts the center of the image on the center of the container.
精彩评论