John Smith
John Smith

Reputation: 1687

Nesting a bunch of divs neatly inside one another with borders

I need your help,

The divs appear to be nested properly (left, top and right) borders line up but at the bottom it seems that they are longer than that of the container div.

See pic here:enter image description here

Here is the HTML coding:

<!DOCTYPE html>
<html>
<head>
    <title>Centered Div</title>
    <style>
    body { background: #000; }
    #wrapper {
        height: 100px;
        width: 500px;
    }

    #wrapper {
        bottom: 50%;
        right: 50%;
        position: absolute;
    }

#container {
    background: rgb(230,230,230);
    left: 50%;
    padding: 10px;
    top: 50%;
    margin: 0;
    padding: 0;
    height: 100%;
    border: 1px solid red;
    height: 100%;
    position: relative;
}
#inner1 {
    height: 100%;
    border: 1px solid blue;
}
#inner2 {
    height: 100%;
    border: 1px solid green;
}

    </style>
</head>
<body>


    <div id="wrapper">
        <div id="container">

            <div id="inner1">

                <div id="inner2"></div>

            </div>

        </div>
    </div>
</body>
</html>

Upvotes: 1

Views: 2769

Answers (1)

Paul Woidke
Paul Woidke

Reputation: 928

The divs are being pushed down by their borders, and the borders of the parent divs. Since a width is not specified, the divs will fill the horizontal space correctly. But since the height of the divs is set to 100%, they are pushed down 1px on the top by the border. Since the border is on the outside of the div, it is not counted as part of the height or width, and therefore not accounted for as part of height:100%.

You can see this more clearly if you change your widths in the CSS to border: 10px solid red/green/blue;.

To correct this, set the box-sizing CSS attribute of the #inner1 and #inner2 divs like this:

-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box;    /* Firefox, other Gecko */
box-sizing: border-box;         /* Opera/IE 8+ */

Upvotes: 3

Related Questions