Html 将 <IMG/> 放在带有 CSS 的 <DIV> 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4958385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
center <IMG/> inside a <DIV> with CSS
提问by Dan
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.
我想在 div 内居中图像。div 的固定宽度为 300px。图像宽度仅在运行时已知。它通常大于 300px,因此图像应居中并左右切割。在这种情况下,margin 0 auto 不起作用。
<!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
感谢您的任何 css 想法
UPDThis interesting task is followed here
UPD这个有趣的任务是在这里遵循
回答by Pekka
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.
给予div
text-align: center
应该工作。(不过,您可能必须将其添加align='center'
为属性才能在 IE6 中工作。)注意:正如@streetpc 所指出的,如果图像比容器宽,则此方法将无法正常工作。
Alternatively, you could also have the image as a background image:
或者,您也可以将图像作为背景图像:
background-image: url(url);
background-position: center top;
回答by mercator
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:
以及以下 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.
在position: relative
对.outer
标有*
那么它只适用于IE6 / 7。如果您喜欢,您可以将它移动到条件 IE 样式表,或者*
完全删除它。需要避免现在相对定位的孩子溢出。
回答by betty.88
To center an image at the center of an html page:
要将图像居中在 html 页面的中心:
<p style="text-align:center; margin-top:0px; margin-bottom:0px; padding:0px;">
<img src="image.jpg" alt="image"/>
</p>
回答by flyingrabbit
You can use CSS transform to position the element:
您可以使用 CSS 变换来定位元素:
div { position: relative; }
img { position: absolute; left: 50%; transform: translateX(-50%); }