通过边距自动的 HTML 中心内容不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15692302/
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
HTML center content through margin auto not working
提问by jason white
I have the following Html code
我有以下 Html 代码
<div id="team">
<h1>Team</h1>
<img src="assets/divider.png" id="divider">
<img src="assets/team.png" id="team_pic">
</div>
The following CSS
以下CSS
div#team {
margin: 0 auto;
margin-left:auto;
margin-right:auto;
right:auto;
left:auto;
}
However, the child elements divider and team pic are all the way to the left. I though margin:auto would center everything.
但是,子元素分隔符和团队图片一直在左侧。我认为 margin:auto 会将所有内容居中。
then I put the following into the child elements.
然后我将以下内容放入子元素中。
div#team img#team_pic {
width:704px;
height:462px;
margin-left:auto;
margin-left:auto;
}
Nope, nothing happen, the elements still to left and not centered.
不,什么也没有发生,元素仍然向左而不是居中。
回答by Sandro
You need to set a width to #team, for example:
您需要将宽度设置为#team,例如:
div#team {
margin: 0 auto;
width: 800px;
}
... which is a shorthand version of:
...这是以下内容的简写版本:
div#team {
margin-top: 0;
margin-left: auto;
margin-bottom: 0;
margin-right: auto;
width: 800px;
}
回答by Gabriel Ferraz
Images are inline level elements by default. You need to use display:block;
if you want your images and margin to work properly.
默认情况下,图像是内联级元素。display:block;
如果您希望图像和边距正常工作,则需要使用。
img{
display: block;
}
回答by Justin Mann
float will upset this too.. float:none;
does the trick if you think it may be inheriting a 'float' directive from another rule somewhere.
float 也会使这 float:none;
不愉快。
回答by btevfik
回答by Hassaan
#team {
margin: auto;
width: 400px;
}
Basically margin depends on width if and only ifwe want to show our div in the center of the page.
当且仅当我们想在页面中心显示我们的 div 时,边距基本上取决于宽度。
回答by Thilanka De Silva
*Use the display:block; for the images classes.*
*使用 display:block; 对于图像类。*