并排使用float <div> </div>

时间:2014-06-17 19:17:16

标签: html css

我似乎对理解float属性

有疑问
<div style="background-color:green;width:40px;height:50px;float:left;"> test </div>
<div style="background-color:blue;width:50px;height:40px"> hello  </div>

我将第一个div浮动到左边,第二个div应该在它旁边,但它只是在它上面,如果我添加到第二个div BTW它可以工作:{{1} }

5 个答案:

答案 0 :(得分:1)

通过将float: left;添加到第二个div,我们可以解决此问题。您也可以在第二个div上使用float: right;

http://jsfiddle.net/x3Lgu/

你需要漂浮两个div。仅浮动一个div会创建其他元素可以包裹的空间以及浮动的空间。在你的情况下看起来很奇怪,因为你将宽度限制得非常窄。如果宽度更大,你会更清楚地看到我的意思。您通常会看到包含文本环绕图像的页面。例如....

http://jsfiddle.net/ErjcN/

注意文本如何环绕图像。这正是您的文档中发生的事情。

答案 1 :(得分:0)

你必须将另一个div也浮动到左边。如果你漂浮两个div,Float可以使用两个div。现在没有浮动的div也是一样的。

所以:

<div style="background-color:green;width:40px;height:50px;float:left;"> test </div>
<div style="background-color:blue;width:50px;height:40px; float: left;"> hello  </div>

看起来很奇怪,但这只是css的工作方式。

答案 2 :(得分:0)

添加一个浮动:左;到你的第二个div也应该把它们放在一起

<div style="background-color:green;width:40px;height:50px;float:left;"> test </div>
<div style="background-color:blue;width:50px;height:40px;float:left"> hello  </div>

答案 3 :(得分:0)

您必须将float: left属性提供给两个div,否则它将无效。

你还可以做的是应用display: inline-block,它会将2 div彼此相邻。

<强> HTML

<div class='first'>First div</div>
<div>Second div</div>

<强> CSS

div {
    float: left;
    width: 50px;
    background-color: blue;
}

.first {
    width: 40px;
    background-color: green;
}

答案 4 :(得分:0)

这是如何运作的......

考虑以下HTML代码段:

<h2>Default Behaviour</h2>
<div style="background-color:green;width:40px;height:50px;float:left;">test</div>
<div style="background-color:lightblue;width:50px;height:40px;">a a a a hello</div>

<br><br>
<h2>New Block Formatting Context</h2>
<div style="background-color:green;width:40px;height:50px;float:left;">test</div>
<div style="background-color:lightblue;width:50px;height:40px; overflow: auto;">a a a a hello</div>

在第一种情况下,我添加了一些单字母词来证明这种行为。 CSS将非浮动元素放置在包含块的顶部和左侧,因为前一个元素是浮动的,因此超出了常规内容流。

CSS然后将浮动元素放置在左上角(尽可能高)并开始包围它周围的流入内容。由于in-flow div具有固定宽度,因此内容被约束到右侧,如浮动元素周围的单个字母所示。

在第二种情况下,我通过分配overflow: auto来建立新的块格式化上下文(scroll也可以,float)。在这种情况下,in-flow元素的左边缘位于浮动元素的右侧,因此浮动元素周围没有文本环绕。

请参阅演示:http://jsfiddle.net/audetwebdesign/Rd3Fp/

结果如下:

enter image description here

相关问题