开发者

Div overflow with padding in Chrome

开发者 https://www.devze.com 2023-02-06 02:29 出处:网络
Can anyone explain why I get a vertical overflow with this code please? <html> <body style=\"width:120px; height:120px; background-color:white;\">

Can anyone explain why I get a vertical overflow with this code please?

<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>

In Chrome 8 it renders like this:开发者_如何学编程

Div overflow with padding in Chrome


I'm assuming you want it to look as it does, but with the green border not protruding outside the blue one, and the whole thing fitting inside 120px * 120px.

You aren't specifying a doctype in that code, so it becomes difficult to make things work between different browsers - some browsers will fall into "quirks mode".

With the code you gave, IE8 for instance stretches the layout to the width of the window.

The first step to make it look consistent is to add a doctype, such as the HTML5 doctype:

<!DOCTYPE html>

Adding that makes it look consistent between Chrome, IE8, Firefox, Opera:

Div overflow with padding in Chrome

..but it also makes it look wrong, and there's no simple way to fix it because you're trying to mix % and px based measurements (a simple fix would be to use just % or just px). Using height: 100% and padding: 20px will make the element too tall because it's total height will be the padding plus the height of the parent element (this is the reason for your "overflow").

So here's some new code which gives the visual effect you're looking for using a different method:

Div overflow with padding in Chrome

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

精彩评论

暂无评论...
验证码 换一张
取 消