center <IMG/> inside a <DIV> with CSS

江枫思渺然 提交于 2019-11-26 17:02:53

问题


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


回答1:


You can make it work if you wrap another element around the image:

<div class="outer">
    <div class="inner"><img src="" alt="" /></div>
</div>

And the following CSS:

.outer {
    width: 300px;
    border: 1px solid red;
    overflow: hidden;
    *position: relative;
}
.inner {
    float: left;
    position: relative;
    left: 50%;
}
img {
    display: block;
    position: relative;
    left: -50%;
}

The position: relative on the .outer is 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.




回答2:


Giving the div text-align: center should work. (You may have to add align='center' as a property for it to work in IE6, though.) Note: As pointed out by @streetpc, this method will not work properly if the image is wider than the container.

Alternatively, you could also have the image as a background image:

background-image: url(url);
background-position: center top;



回答3:


To center an image at the center of an html page:

<p style="text-align:center; margin-top:0px; margin-bottom:0px; padding:0px;">
<img src="image.jpg" alt="image"/>
</p>



回答4:


You can use CSS transform to position the element:

div { position: relative; } 
img { position: absolute; left: 50%; transform: translateX(-50%); }


来源:https://stackoverflow.com/questions/4958385/center-img-inside-a-div-with-css

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!