I want to center image inside a div. The div has fixed width 300px. The image width is known only at runtime. It usually is bigger then 300px, so image should be centered and cut right and left. margin 0 auto does not work in this case.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">
div{width:300px;border:1px solid red; overflow:hidden}
img{
/* NOTE!!!!
margin:auto; doesn't work when image width is bigger than div width
image width is known only at runtime!!!
*/
}
</style>
</head>
<body>
<div>
<img src="" />
</div>
</body>
</html>
Thanks for any css ideas
UPD This interesting task is followed here
You can make it work if you wrap another element around the image:
And the following CSS:
The
position: relativeon the.outeris marked with*so it only applies to IE6/7. You could move it to a conditional IE stylesheet if that’s what you prefer, or remove the*altogether. It’s needed to avoid the now relatively positioned children from overflowing.