html - 为什么我不能以边距 : 0 auto? 为中心

标签 html css margin

我有一个 #header100% 宽度 的 div,在那个 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>

最佳答案

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

#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;
}

关于html - 为什么我不能以边距 : 0 auto? 为中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/963636/

相关文章:

javascript - Accordion 可点击并悬停?

android - 为什么在使用 wrap_content 时会忽略 layout_marginBottom?

html - Photoset 之间的边距

html - 文本在跨度内右对齐

javascript - 如何调试应用了 css 的 html 代码?

html - 如何在文本上制作一个向内倾斜的边框?

css - HTML5 视频 : full screen without borders?

javascript - 模板渲染后的 Angular 变化检测

html - x 滚动条的 CSS 问题

javascript - 滚动 div 代码