【问题标题】:Margin 0 auto will not center two of my divsMargin 0 auto 不会将我的两个 div 居中
【发布时间】:2014-12-04 16:05:36
【问题描述】:

所以,我试图将我的三个 div 放在页面的中心,#header、#nav 和 #headerImg。我似乎无法使用 margin: 0 auto; 将我的 #header 和 #nav div 居中。尽管。当我刷新页面时,它们似乎卡在页面的左侧。

这是我页面的 style.css:

div#header{      //I only have one image here.
    position:absolute;
    padding: 10px 20px;
    width: 960px;
    height: 49px;
    top: 0px;
    background-color: #2E5E8D	
}

div#nav{         //I have 4 links here
    position:absolute;
    margin: 0 auto;
    padding: 10px 20px;
    width: 960px;
    height: 20px;
    top: 69px;
    background-color: #2E5E8D
}

div#headerImg{   //I have one image here, 
    position: relative;
    display: block;
    margin: 0 auto;
    width: 1000px;
    top: 95px;
}

div#content{
    position:relative;
    top:109px;
    width:1000px;
    display: block;
    margin: 0 auto;
}

div#content a{
    color: blue;
    text-decoration: none;
}

#content a:hover{
    color: red;
    text-decoration: underline;
}
	
#content dt{
    margin-top: 10px;
}

div#footer{
    position: relative;
    margin: 0 auto;
    top: 109px;
    background-color: #333333;
    color: white;
    text-align: center;
    font-size: 14px;
    width: 1000px;
    padding: 10px;
}

我的#header#nav 的宽度必须根据教练的要求设置为960px,我确信他希望我的#headerImg 中的图像在我的#header div,但我无法从重叠中获取图像。因此,这是我可以居中的 3 个 div 中唯一的一个。

我尝试在两者上都使用margin: 0 auto;display: block,但它们似乎不起作用。我尝试使用margin: 0 10%,它似乎在我的计算机上工作,但它在另一台计算机上未对齐。我在代码中的 cmets 只是为了显示我在 div 中的内容。

【问题讨论】:

  • margin:0 auto; 不适用于绝对定位的元素。

标签: html css


【解决方案1】:

尝试添加 div#header 和 div#nav 如下规则:

margin-left: -500px;
left: 50%;

【讨论】:

  • 谢谢!做到了,一旦我这样做了,我也必须将我的#headerImg 更改为相同的规则。一切看起来都很好。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2016-06-19
  • 2013-12-11
  • 2015-10-24
  • 2015-07-09
  • 1970-01-01
  • 2010-11-01
  • 2018-09-04
  • 1970-01-01
相关资源
最近更新 更多