为什么这个父元素没有完全包含它的子元素?

时间:2012-07-11 09:59:21

标签: html css

当我的浏览器窗口最大化时,此代码工作正常,子项包含在父项中,父项跨越浏览器的宽度。但是,当浏览器窗口小于子元素宽度时,父元素无法包含它(在chrome 20和firefox 13中测试)

http://jsfiddle.net/x9duU/

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Example</title>

        <style type="text/css">
            #toolbar {
                background-color:#cccccc;
                padding:10px 0;
            }

            #nav {
                background-color:#00cccc;
                margin:0 auto;
                width:1000px;
            }
        </style>
    </head>
    <body>

        <div id="toolbar">
            <div id="nav">NAVIGATION</div>
        </div>

    </body>
</html>

我可以通过浮动父级并给出最小值为100%来解决问题,但这似乎是错误的。我该怎么做才能解决这个问题?

4 个答案:

答案 0 :(得分:2)

#toolbar是一个blocklevel元素,默认为width:100% - 父元素的宽度为100%。这是它遵守的规则,让孩子在宽度超过的情况下溢出。你可以通过设置overflow属性来调整它。

但是,如果您希望父div将其子宽度考虑在内,请设置最小宽度(等于子宽度)重要说明:您必须考虑可能的边距和填充(或更改框 - 模型到边框)。

#toolbar {
   min-width:1000px;
}​

答案 1 :(得分:0)

解决此问题的最简单,最合适的方法是remove the 1000px width from #nav(它在那里做了什么?)。

或者,给#toolbar overflow: hidden achieve the same visual effect

答案 2 :(得分:0)

在导航栏上尝试min-width:1000px

 #nav {
        background-color:#00cccc;
        margin:0 auto;
        min-width:1000px;/*New style*/
    }​

答案 3 :(得分:0)

        #toolbar {
            background-color:#cccccc;
            padding:10px 0;

            overflow: hidden;
        }
相关问题