2015-07-20 68 views
1

在我的CSS我有以下幾點:如何放置css div容器「text-align:center;」

的style.css

* { 
    margin: 0; 
    padding: 0; 
} 

body { 
    width: 100%; 
    font-family: 'Cabin', sans-serif; 
} 

/*.clear { 
    clear: both; 
}*/ 

.clear:after { 
    display: block; 
    clear: both; 
    visibility: hidden; 
    content: ""; 
    height: 0; 
} 

/* HEADER BLOCK */ 

.header-background { 

    padding-top: 50px; 
} 

.header-background > div:first-child { 
    width: 100%; 
    background: #232323; 
} 

.header { 
    background: #232323; 
    color: #B2B2B2; 
    width: 80%; 
    margin: auto; 
} 

.header a { 
    text-decoration: none; 
    color: white; 
} 

.header a:active { 
    color: #19A3A3; 
} 

#nav { 
    position: relative; 
    display: block; 
    height: 55px; 
    line-height: 55px; 
    width: 100%; 
    max-width: none; 
    margin: 0; 
    background: #333; 

    z-index: 1; 
    border-bottom: 1px solid #666; 
    font-weight: 600; 
    font-family: helvetica, arial, sans-serif; 
    font-size: 14px; 
} 

#nav, #nav * { 
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */ 
    -moz-box-sizing: border-box; /* Firefox, other Gecko */ 
    box-sizing: border-box;   /* Opera/IE 8+ */ 
} 

.nav-item { 
    color: #fff; 
    text-transform: uppercase; 
    text-decoration: none; 
} 


/* Desktop */ 

#desktop-nav .nav-item { 
    display: block; 
    padding: 0 20px; 
    float: right; 

    -webkit-transition: color 200ms linear; 
    -moz-transition: color 200ms linear; 
    -ms-transition: color 200ms linear; 
    -o-transition: color 200ms linear; 
    transition: color 200ms linear; 
} 

#desktop-nav .nav-item:hover, #desktop-nav .nav-item:active { 
    opacity: 0.7; 
} 

而且我有以下的html:

<body> 
    <div class="header-background"> 
     <!-- <div> --> 
     <div id="nav"> 
      <nav id="desktop-nav"> 
       <a class="nav-item" href="#1">Github</a> 
       <a class="nav-item" href="#2">About</a> 
       <a class="nav-item" href="#3">Community</a> 
       <a class="nav-item" href="#4">Docs</a> 
      </nav> 
     </div>  
    </div> 
</body> 

現在我得到的觀點: - This view

但我想要像這樣的視圖: - Like that

菜單應該在中間。我已經使用text-align: center;但它沒有執行。我做錯了什麼?

回答

1

更改此

#nav { 
    margin: 0 auto; //added this 
    width: 400px;  //added this 
    position: relative; 
    display: block; 
    height: 55px; 
    line-height: 55px; 
    max-width: none; 
    background: #333; 
    z-index: 1; 
    border-bottom: 1px solid #666; 
    font-weight: 600; 
    font-family: helvetica, arial, sans-serif; 
    font-size: 14px; 
} 

小提琴:https://jsfiddle.net/fuehunfz/

-1

在CSS類中使用以下CSS樣式

margin:0 auto;

+0

哪個類???? 「頭背景??」但是沒有什麼... – Preeti

0

目前,#desktop-nav居中,但它的寬度爲100%,因此您需要將它縮小至inline-block

然後在#nav`上的text-align:center將居中。

#nav { 
     text-align: center; 
    } 

#desktop-nav { 
    display: inline-block; 
} 

JSfiddle Demo