为什么子div超出了它们的父div?

时间:2014-08-29 15:30:52

标签: html css

我觉得这很愚蠢,但这是一个非常简单的问题,不明白如何解决。在下面的代码中,为什么容器,主要和辅助div扩展到标题之外?我知道这是因为我已经分配给容器的填充,但我已经为html元素分配了一个最大宽度。 header元素遵循最大宽度,但容器及其子div不是。我在这里看过类似的问题,但没有看到任何我认为与我的特殊情况相关的问题。这是怎么回事?

感谢。

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>

1 个答案:

答案 0 :(得分:4)

容器上的padding: 1emwidth:100%一起构成实际宽度100% + 2em

您应该将box-sizing: border-box;添加到.cointainer以确保宽度为100%(example)。

相关问题