2014-02-27 88 views
0

所以我有以下CSS背景圖片:CSS位置固定和保證金0汽車

body{ 
    background-image:url(cover.jpg); 
    background-repeat:no-repeat; 
    background-position:center; 
    background-attachment:fixed; 
} 

和背景圖像是1280像素寬。所以我希望我的導航欄固定並以背景爲中心。但我遇到問題。這是我的代碼。

#navigation { 
margin: 0 auto; 
position:fixed; 
top: 0; 
width: 1280px; 
height: 35px; 
padding-top: 10px; 
background-color: #000000; 
} 

但導航欄將固定但不居中。如果我刪除固定,它將居中,但它不固定。

任何方式來實現這一目標?

+0

可能重複[位置絕對和保證金:汽車(http://stackoverflow.com/questions/15961232/position-absolute-and -margin-auto) – essmahr

+0

爲你的html添加片段將有助於 – JLewkovich

+0

如何添加html幫助? ' <鏈路的rel = 「樣式表」 類型= 「文本/ CSS的」 href = 「page.css」>

' – Jared

回答

8

可以進行以下

#navigation { 
    position:fixed; 
    left:0; 
    right:0; 
    margin-left:auto; 
    margin-right:auto; 
    width: 1280px; 
    height: 35px; 
    padding-top: 10px; 
    background-color: #000000; 
} 
+0

完美!謝謝。 – Jared

0

風格創建.container格:

//no float! 
width:960px; 
possition:relative; 
margin:0; //centers 

然後withing這個容器在容器中心的建立固定的導航欄:)

position:fixed; 
float:left; 
width:100%; 
height:50px; 

所以現在導航欄棒。

您可能需要編輯的代碼只有top

0

固定和自動是兩種不同的東西,你不能一起調用它們。更好的解決方案是創建一個容器div,使用margin:0 auto將它添加到body中,然後再創建另一個div,並將導航放在那裏。您可能還想要在該容器div上設置高度。

<div class="container"> 
    <div class="nav"> 
     <!-- nav here --> 
    </div> 
</div> 
1
.fixed-centered { 
    position: fixed; 
    left: 50%; 
    transform: translate(-50%); 
}