为什么我不能以保证金为中心:0自动?

zec*_*ude 125 html css margin

我有一个#headerdiv,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>
Run Code Online (Sandbox Code Playgroud)

Pat*_*and 130

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

#header ul {
    margin: 0 auto;
    width: 90%;
}
Run Code Online (Sandbox Code Playgroud)

编辑:好的,我现在已经看过testpage了,这就是我认为你想要它的方式:

#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;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果ul的宽度是动态的怎么办?我想在以后用PHP动态地在li中使用不同的文本,所以我试图预测到这一点. (2认同)
  • 是的,那么你不能使用margin:auto; (2认同)

小智 42

内联块覆盖整条线(从左到右),因此左边和/或右边距不会在这里工作.你需要的是一个块,一个块在左边和右边有边框,所以可以受到边距的影响.

这是它对我有用的方式:

#content {
display: block;
margin: 0 auto;
}
Run Code Online (Sandbox Code Playgroud)


kal*_*nov 13

为什么不?

#header {
    text-align: center;
}

#header ul {
    display: inline;
}
Run Code Online (Sandbox Code Playgroud)