HTML,嵌套Div问题

时间:2011-04-05 07:32:27

标签: html nested

在我的页面中,我有三个部分Header,Body和Footer。 在身体我有三个div。第一个div包括另外两个小div。

我写了这个CSS代码:

#body_container{
    margin: 10px 160px;
    height: auto;
    width: 100%;
    clear: both;
    border: 1px solid #3F0;
}

div.body_contents{
    height: auto;
    width: 74%;
    float: left;
    border: 1px solid #960;
}

div.sidebar{
    height: auto;
    width: 25%;
    float: right;
    border: 1px solid #F0F;
}

但是当我检查它时,div不在我的框架内。我给了160px的左右边距。我该怎么办? 感谢

enter image description here

2 个答案:

答案 0 :(得分:1)

我讨厌使用百分比,因为它们取决于其他事物。

我通常使用静态值执行某些操作,例如:

#body_container{
    margin: 10px auto; /** The auto will make this div centered to the page **/
    width: 1000px; /** suppose you want this width **/
    clear: both;
    border: 1px solid #3F0;
}

div.body_contents{
    width: 748px; /** The width of the main part, -2px (for the border) **/
    float: left;
    border: 1px solid #960;
}

div.sidebar{
    width: 248px; /** The width of the side bar, -2px (for the border) **/
    border: 1px solid #F0F;
}

当然,如果你想要你的主div的宽度改变浏览器的大小(就像你的原始CSS一样),我的答案不起作用。

但我建议你不要根据浏览器更改宽度,因为它会根据窗口改变页面的组织。

答案 1 :(得分:1)

这很简单,margin增加了元素的最终渲染宽度(即父级宽度的160 x 2 + 100%,因此它是溢出的),所以你可能想要制作它,例如,外部div,宽度为79%,左右边距各为10%(因此总数为99%,少了1%以允许一些空间用于边界等等......虽然这通常不是我的工作方式)

示例:http://jsfiddle.net/MKjwU/6/

还有一件事:要清除花车,你不要像在你的例子中那样清除它......

使用额外的div,如下所示:http://jsfiddle.net/MKjwU/7/

或使用此技巧:http://www.quirksmode.org/css/clearing.html

请参阅:http://jsfiddle.net/MKjwU/8/