2013-03-31 59 views
0

理解在源代碼中低於該網站的示例頁面的:CSS:內聯塊幫助中心的導航欄 - 需要的工作

http://6.470.scripts.mit.edu/css_exercises/exercise5.html 

<head> 
<style> 
body 
{ 
    font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; 
    background-color: #bbbbbb; 
} 
#container 
{ 
    width:1000px; 
    background-color:#dddddd; 
    text-align: center; 
    margin: auto; 
} 
#navigation 
{ 
    display: inline-block; 
    margin-top:20px; 
} 

#navigation_bar 
{ 
    list-style-type:none; 
    margin:auto; 
    padding:0; 
    overflow:hidden; 
    font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; 
} 
#navigation_bar li 
{ 
    float:left; 
} 
#navigation_bar a:link, #navigation_bar a:visited 
{ 
    display:block; 
    width:120px; 
    font-weight:bold; 
    color:#FFFFFF; 
    background-color:#993738; 
    text-align:center; 
    padding:4px; 
    text-decoration:none; 
    text-transform:uppercase; 
} 
</style> 
</head> 
<body> 
<div id="container"> 
    <div id="header"> 
     <h1 id="big_title">6.470 Web Programming Competition</h1> 
    </div> 
    <div id="navigation"> 
     <ul id="navigation_bar"> 
      <!--On a real website, you would put the URL you want to navigate to inside href--> 
      <li><a href="#home">Home</a></li> 
      <li><a href="#materials">Materials</a></li> 
      <li><a href="#competition">Competition</a></li> 
      <li><a href="#pastyears">Past Years</a></li> 
      <li><a href="#about">About</a></li> 
     </ul> 
    </div> 
</body> 

導航欄的中心只有當顯示:內聯-block在div#導航中使用。如果它被刪除,那麼導航欄根本不居中。即使是margin:auto for ul#navigation_bar也無濟於事。如果爲ul ## navigation_bar提及寬度,那麼它可以居中放置導航欄。我的問題是,整個事情是如何工作的,即如何顯示:inline-block使導航欄居中,固定寬度如何使ul#navigation_bar也起作用? margin:auto如何在其他情況下沒有影響?

非常感謝您的幫助澄清。

+0

你有這個我們可以看/玩的演示嗎? – qooplmao

回答

1

<ul>是一個塊元素,默認情況下會嘗試佔用其容器的全部寬度。由於父項爲inline-block,因爲inline-block元素are formatted as a block box的內容只增長到其內容的寬度(<li> s)。這受block formatting context - <ul>接觸其容器的邊緣。如果在<div>上未指定display: inline-block,則佔用全部寬度,<ul>margin: 0 auto;也不起作用。

請注意,您也可以將display: inline-block放在<ul>本身上以減小其寬度並使margin: 0 auto有效。