2011-01-19 38 views
2

任何人都可以解釋爲什麼我會得到這個代碼的垂直溢出嗎?在Chrome中使用填充進行Div溢出

<html> 
    <body style="width:120px; height:120px; background-color:white;"> 
     <div style="padding:20px; background-color:blue;"> 
      <div style="width:100%; height:100%; background-color:white"> 
       <div style="padding:20px; background-color:green;"> 
        <div style="width:100%; height:100%; background-color:white"> 
        </div> 
       </div> 
      </div> 
     </div> 
    </body> 
</html> 

在Chrome中8它呈現這樣的:

alt text

回答

3

我假設你想讓它看起來是這樣,但隨着綠色邊框不突出藍色的外面,整個東西裝在120px * 120px裏面。

您沒有在該代碼中指定文檔類型,因此很難在不同瀏覽器之間運行,有些瀏覽器會陷入「怪癖模式」。

隨着你給的代碼,例如IE8將佈局拉伸到窗口的寬度。

的第一步,使它看起來一致的是添加一個文檔類型,如HTML5文檔類型:

<!DOCTYPE html>

添加使得它看起來Chrome瀏覽器,IE8,Firefox,歌劇之間是一致的:

..但它也使得它看上去是錯誤的,而且也沒有簡單的方法來解決這個問題,因爲你試圖混合%px基於measureme nts(一個簡單的解決辦法是隻使用%或只是px)。使用height: 100%padding: 20px會使元素太高,因爲它的總高度將是填充加上父元素的高度(這是「溢出」的原因)。

所以這裏的一些新的代碼,讓你正在尋找使用不同的方法,在視覺效果上:

Live Demo

<!DOCTYPE html> 
<html> 
<body style="width:120px; height:120px"> 
    <div style="background:blue; width:100%; height:100%; position:relative"> 
     <div style="background:green; position:absolute; top:20px; right:20px; bottom:20px; left:20px"> 
      <div style="background:white; position:absolute; top:20px; right:20px; bottom:20px; left:20px"></div> 
     </div> 
    </div> 
</body> 
</html> 
+0

完美!謝謝! – rob 2011-01-19 19:20:47

2

你正在尋找的答案可以發現本頁內容:

Iframe 100% height inside body with padding

簡而言之,HTML5能夠拯救。將此CSS添加到您的DIV並解決問題:

box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box;