当我将div标签浮动到HTML中的另一个div中时

时间:2015-07-01 15:15:24

标签: html css

当我想将div浮动到另一个内部时,会出现问题。

<div id="main">
    <div id="anotherDiv">
        <h1>Test</h1>
    </div>
</div>

这是我的样式表:

#main{ background-color:red; padding:20px; }
#anotherDiv{ background-color:blue; }

这是我没有浮动的页面:

enter image description here

但是当我添加以下样式时,这是我的阶梯表:

#anotherDiv{ float:left; }

enter image description here

但我想要这样的事情:

www.erfan21.persiangig.com/document/03.png

我该怎么办?

3 个答案:

答案 0 :(得分:1)

你需要清除浮动。
这是工作小提琴:

&#13;
&#13;
#main{ background-color:red; padding:20px; }
#anotherDiv{ background-color:blue; }
#anotherDiv{ float:left; }
&#13;
<div id="main">
    <div id="anotherDiv">
        <h1>Test</h1>
    </div>
    <div style="clear: both;"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

只需将overflow:auto添加到#main

#main {
    background-color:red;
    padding:20px;
    overflow:auto;
}

jsFiddle example

将在没有任何不必要的HTML元素的情况下恢复您寻找的父div的行为。

答案 2 :(得分:0)

您也可以尝试display: inline-block;

DEMO