Why do child divs go outside of their parent div?

It seems silly to me to ask this, but it is a very simple problem that does not understand how to solve it. In the code below, why do container, main and secondary divs go outside of the header? I understand this is happening because of the padding I assigned to the container, but I assigned the max-width to the html element. The header element obeys its maximum width, but the container and its child divs are not. I have looked at similar questions here, but did not see anything that I thought was relevant to my particular situation. What's going on here?

Thank.

enter image description here

test.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Test</title>
    <link rel="stylesheet" href="../reset.css" />
    <style type="text/css">
        html {
            max-width: 960px;
            margin: 0 auto;
            position: relative;
        }
        header { 
            height: 2.5em;
            background: #2a3744; 
            color: #fff;
        }
        body {
            font-size: 100%;
            -moz-box-sizing: border-box;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
        }
        .container {
            width: 100%;
            padding: 1em;
            margin: 0 auto;
            background: #ccc;
        }
        .main { background: #cf6; }
        .secondary { background: #fc6; }
    </style>
</head>
<body>
    <header role="banner">
        header
    </header>
    <div class="container">
        <div class="main">
            main           
        </div>
        <div class="secondary">
            secondary
        </div>
    </div>
</body>
</html>

      

+3


source to share


1 answer


padding: 1em

on the container along with width:100%

makes the actual width 100% + 2em

.



You should add box-sizing: border-box;

in .cointainer

to make sure the width is 100% ( example ).

+3


source







All Articles