为什么我不能以 margin: 0 auto 居中?

问题描述 投票:0回答:6

我有一个

#header
div,它是
100% width
,在那个div中我有一个无序列表。我已将
margin: 0 auto
应用到无序列表,但它不会在标题 div 中居中。

谁能告诉我为什么?我认为如果我定义父 div 的宽度,那么无序列表应该能够以

margin: 0 auto
居中。我错过了什么?

这是我的代码:

<style>

* {
    margin: 0;
    padding: 0;
}

#header {
    width: 100%;    
    background-color: #333;
    min-height: 160px;
    font-family:Arial, Helvetica, sans-serif;
}

#sitename {
    font-size: 50px;
    width: 620px;
    margin:0 auto;
    padding-top: 35px;
    color:#999;
}

#header ul {
    float: right;
    margin: 0 auto;
}

#header ul li {
    float: left;
    padding-right: 20px;
    list-style-type: none;
    font-size: 20px;
}

</style>

</head>

<body>

<div id="header">
    <h1 id="sitename">Photography Auction Site</h1>

    <ul>
        <li>List of Photos</li>
        <li>Image Gallery</li>
        <li>Contact Us</li>
    </ul>
</div>

</body>
</html>
html css margin
6个回答
149
投票

您需要定义居中元素的宽度,而不是父元素。

#header ul {
    margin: 0 auto;
    width: 90%;
}

编辑:好的,我现在已经看到了测试页,这就是我认为您想要的方式:

#header ul {
    list-style:none;
    margin:0 auto;
    width:90%;
}

/* Remove the float: left; property, it interferes with display: inline and 
 * causes problems. (float: left; makes the element implicitly a block-level
 * element. It is still good to use display: inline on it to overcome a bug
 * in IE6 and below that doubles horizontal margins for floated elements)
 * The styles below is the full style for the list-items. 
 */
#header ul li {
    color:#CCCCCC;
    display:inline;
    font-size:20px;
    padding-right:20px;
}

56
投票

行内块覆盖整行(从左到右),因此左边和/或右边的边距在这里不起作用。你需要的是一个块,一个块在左边和右边有边框,所以可以受到边距的影响。

这对我来说是这样的:

#content {
display: block;
margin: 0 auto;
}

15
投票

为什么不呢?

#header {
    text-align: center;
}

#header ul {
    display: inline;
}

3
投票

我不知道为什么第一个答案是最好的,我试过了但实际上没有用,正如@kalys.osmonov所说,你可以把

text-align:center
header
,但你必须让
ul
作为
inline-block
而不是
inline
,而且您还必须注意
text-align
可以继承,这在某种程度上是不好的,所以更好的方法(不在IE 9以下工作)是使用
margin
transform 
.只需从
float right
中删除
margin;0 auto
ul
,如下所示:

#header ul {
   /* float: right; */
   /* margin: 0 auto; */
   display: inline-block;
   margin-left: 50%; /* From parent width */
   transform: translateX(-50%); /* use self width which can be unknown */
  -ms-transform: translateX(-50%); /* For IE9 */
}

如果您不关心IE8等,这种方式可以解决使

ul
中心动态宽度的问题


0
投票

我们可以设置 ul 标签的宽度然后它会居中对齐。

#header ul {
    display: block;
    margin: 0 auto;
    width: 420px;
    max-width: 100%;
}

0
投票

使用它在绝对位置容器 = 你的容器中居中一个 div。

container { 
left: 50%;
transform: translateX(-50%);
}
© www.soinside.com 2019 - 2024. All rights reserved.