Html 在 div 中居中图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2134333/
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
Centering an image within a div
提问by Dan
I have already set the border of an image within a div
to be none. I now want to center that image within its containing div. I have tried using the margin: 0 auto;
but that did not work.
我已经将 a 中图像的边框设置div
为无。我现在想将该图像置于其包含的 div 中。我试过使用 ,margin: 0 auto;
但没有用。
I am sure I am overlooking something stupid but I would like to enlist the help of the stackoverflow community so this doesn't take me an hour of staring at the screen to figure out. Thanks a lot.
我确信我忽略了一些愚蠢的事情,但我想寻求 stackoverflow 社区的帮助,所以这不需要我盯着屏幕一个小时才能弄清楚。非常感谢。
<body>
<div id="wrapper">
<div id="banner">
<img src="logo3.png"/>
<!--<img src="kslf_logo.png"/>
<img src="logo2.png" title="Katie Samson Lacrosse Festival Logo"/>-->
<div id="social_network">
<a href="#" target="_blank" title="Check out the Facebook Page!">Facebook</a>
</div>
</div>
</div>
</body>
Here is the CSS...
这是CSS...
#banner {
height: 100px;
width: 960px;
padding-bottom: 10px;
}
#banner img {
border: none;
margin: 0 auto;
}
回答by Paul D. Waite
Try setting the image's display
property to block
:
尝试将图像的display
属性设置为block
:
banner {
height: 100px;
width: 960px;
padding-bottom: 10px;
}
banner img {
border: none;
display: block;
margin: 0 auto;
}
回答by nickelleon
Applying text-align: center
to your banner div will center its inline and inline-block children (which encompasses the img tag).
应用于text-align: center
您的横幅 div 将使其内联和内联块子项(包含 img 标签)居中。
The reason why your code wasn't working is because margin: 0 auto
will only center block elements.
您的代码不起作用的原因是因为margin: 0 auto
只会将块元素居中。
回答by Malathy
After many exhaustive tries to center align an image in a div (vertically and/or horizontally), I understood the following.
To vertically center align an image in a div.
在多次尝试将图像居中对齐(垂直和/或水平)后,我理解了以下内容。
垂直居中对齐 div 中的图像。
.div {
display:flex;
justify-content:center
}
To horizontally center align an image in a div.
水平居中对齐 div 中的图像。
.div {
display:flex;
align-items:center;
}
To center both vertically and horizontally an image in a div, there are 2 options (1)
要在 div 中垂直和水平居中图像,有 2 个选项 (1)
div {
display:flex;
align-items:center;
justify-content:center;
}
(2)
(2)
.div {
display:flex
}
.div > img {
margin: auto
}
回答by roman
horizontal: just try
水平:试一试
text-align:center;
:)
:)
回答by Gabriele Petrioli
Either
任何一个
banner {
height:100px;
text-align:center;
width:960px;
padding-bottom:10px;}
or if the img is of specific size then
或者如果 img 具有特定大小,则
banner img {
display:block;
width: <somevalue>px;
border:none;
margin:0 auto;
}
will work ..
将工作 ..
回答by Hunter
I believe it is just margin: auto;
. No zero needed.
我相信这只是margin: auto;
. 不需要零。