Html CSS 边距:0 自动;不适用于 <img> 标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26477480/
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
CSS Margin: 0 Auto; is not working on <img> tag
提问by Drazzah
My markup is simple, and I'm using inline CSS. My goal is to get the image centered using margin: 0 auto;
in the style
HTML attribute. Here's code that I have tried:
我的标记很简单,而且我使用的是内联 CSS。我的目标是margin: 0 auto;
在style
HTML 属性中使用图像居中。这是我尝试过的代码:
<div style="width: 100%;">
<img src="http://dummyimage.com/200x300/000000/fff" style="margin: 0 auto;"/>
</div>
Why is the CSS not centering my <img>
?
为什么 CSS 不居中我的<img>
?
回答by Fahad Hasan
You must use display: block
to make margin: 0px auto
have any effect.
你必须使用display: block
使margin: 0px auto
有任何效果。
<div style="width: 100%;">
<img src="http://placekitten.com/g/200/300" style="display: block; margin: 0px auto;">
</div>
回答by Talmid
Your style attribute syntax is wrong on the div. Also, change the style on the img tag like so:
您的样式属性语法在 div 上是错误的。此外,更改 img 标签上的样式,如下所示:
<div style="width:100%">
<img src="https://4c206b86fe5a0219d31bb1ae55c8bbdc3f028879-www.googledrive.com/host/0BzEiAml5ygAeU3N6QTRUUW53Vjg/" width="50%" height="auto" style="margin:0 auto; display:block">
</div>
回答by walther
Img
is an inline element, so width: 0 auto
won't work, unless you set display: block
. Or you can center it with text-align: center
, which is a bit weird, but should work similarly.
Img
是一个内联元素,所以width: 0 auto
不会工作,除非你设置display: block
. 或者你可以用 将text-align: center
它居中,这有点奇怪,但应该类似。
Also, you should consider stop using inline styles. It makes html markup harder to read, harder to maintain etc. Styles belong to separate css files and you should try to avoid inline styles whenever possible. (and html attributes like width, height etc AS WELL!)
此外,您应该考虑停止使用内联样式。它使 html 标记更难阅读、更难维护等。样式属于单独的 css 文件,您应该尽可能避免使用内联样式。(以及宽度、高度等 html 属性!)
Well, and also margin-left:0 auto; margin-right:0 auto;
isn't really valid. The correct form would be either
嗯,也不margin-left:0 auto; margin-right:0 auto;
是真的有效。正确的形式是
margin: 0 auto;
or
或者
margin-left: auto;
margin-right: auto;
回答by fubbe
text-align: center;
On image tags seems not to be w3c valid anyway.
无论如何,图像标签似乎都不是 w3c 有效的。
display: block;
margin: 0 auto;
Should be!
应该!