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

我有一个#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>


慕姐8265434
浏览 471回答 3
3回答

莫回无

您需要定义要居中的元素的宽度,而不是父元素。#header ul {&nbsp; &nbsp; margin: 0 auto;&nbsp; &nbsp; width: 90%;}编辑:好的,我现在已经看过testpage了,这就是我认为你想要它的方式:#header ul {&nbsp; &nbsp; list-style:none;&nbsp; &nbsp; margin:0 auto;&nbsp; &nbsp; width:90%;}/* Remove the float: left; property, it interferes with display: inline and&nbsp;&nbsp;* causes problems. (float: left; makes the element implicitly a block-level&nbsp;* element. It is still good to use display: inline on it to overcome a bug&nbsp;* in IE6 and below that doubles horizontal margins for floated elements)&nbsp;* The styles below is the full style for the list-items.&nbsp;&nbsp;*/#header ul li {&nbsp; &nbsp; color:#CCCCCC;&nbsp; &nbsp; display:inline;&nbsp; &nbsp; font-size:20px;&nbsp; &nbsp; padding-right:20px;}

神不在的星期二

内联块覆盖整条线(从左到右),因此左边和/或右边距不会在这里工作。你需要的是一个块,一个块在左边和右边有边框,所以可以受到边距的影响。这是它对我有用的方式:#content {display: block;margin: 0 auto;}

慕少森

我不知道为什么第一个答案是最好的,我尝试过了,其实不是工作,如@ kalys.osmonov说,你可以给text-align:center到header,但你必须做ul的inline-block,而不是inline,也必须注意这text-align可以继承在某种程度上不好,所以更好的方法(不在IE 9下工作)是使用margin和transform。只是删除float right,并margin;0 auto从ul,象下面这样:#header ul {&nbsp; &nbsp;/* float: right; */&nbsp; &nbsp;/* margin: 0 auto; */&nbsp; &nbsp;display: inline-block;&nbsp; &nbsp;margin-left: 50%; /* From parent width */&nbsp; &nbsp;transform: translateX(-50%); /* use self width which can be unknown */&nbsp; -ms-transform: translateX(-50%); /* For IE9 */}ul如果不关心IE8等,这种方式可以解决制作动态宽度中心的问题。
打开App,查看更多内容
随时随地看视频慕课网APP