2011-01-19 41 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;