2014-02-07 157 views
1

請看看這段代碼:填充會導致水平滾動 - 它增加了寬度

<html> 
<head> 
<style type="text/css"> 
html, body{ 
width:100%; 
height:100%; 
margin:0px; 
} 

#header{ 
width:100%; 
height:100px; 
position:fixed; 
display:inline-block; 
background-color:red; 
padding:0 10px 10px 10px; 
} 
</style> 
</head> 
<body> 
    <div id="header"> 
     <div id="header-container"> 
     </div> 
    </div> 
</body> 
</html> 

這裏是demoheader必須從左,右和底部有100%的寬度和10px的填充。請看看這幅畫

enter image description here

這是#header由螢火蟲佈局。因爲你可以看到右邊的填充不在圖像中,因爲10px填充被添加到#header寬度(你可以測試它)。我怎樣才能爲#header設置100%的寬度,併爲左側,右側和底部填充10px的寬度而不增加寬度?

回答

4

試試這個

* , *:before, *:after{ 
    box-sizing:border-box; 
    -moz-box-sizing:border-box; 
    -webkit-box-sizing:border-box; 
    -ms-box-sizing:border-box; 
    } 

#header{ 
width:100%; 
height:100px; 
position:fixed; 
display:inline-block; 
background-color:red; 
padding:0 10px 10px 10px; 
box-sizing:border-box; /** add this **/ 
-moz-box-sizing:border-box; /** add this **/ 
-webkit-box-sizing:border-box; /** add this **/ 
-ms-box-sizing:border-box; /** add this **/ 
} 
1

嘗試使用margin ..或減少您的填充區域的寬度。

#header{ 
    width:98%; 
    height:100px; 
    position:fixed; 
    display:inline-block; 
    background-color:red; 
    margin:0 1% 10px 1%; 
} 

填充

的襯墊清除圍繞元素的含量(邊界內)的區域。填充受元素背景顏色的影響。

保證金

保證金清除的區域周圍的元件(的邊界之外)。邊距沒有背景顏色,並且完全透明。

+0

感謝您的回覆,所以'header'和'header-container'的寬度一定要多少? – Drupalist

+0

請檢查這個http://jsfiddle.net/3hVvW/4/ .. –

1

那麼它似乎想要想要全寬與填充。爲此,你可以嘗試下面的代碼:

#header{ 
width: initial; 
height:100px; 
position:fixed; 
display:inline-block; 
background-color:red; 
padding:0 10px 10px 10px; 
} 

我只是希望這會給人的慾望輸出。

3

CSS計算運算符可能證明是有幫助的。有了它,您可以調整指定左/右填充或左/右邊距時可以「拋棄」的寬度。由於您指定了20px的總左/右填充,因此您需要使用20px來減去20px。

#header{ 
width: calc(100% - 20px); 
height:100px; 
position:fixed; 
display:inline-block; 
background-color:red; 
padding:0 10px 10px 10px; 
}