gpt4 book ai didi

html - div 不会 float 在前面的非 float div 旁边

转载 作者:搜寻专家 更新时间:2023-10-31 22:34:31 25 4
gpt4 key购买 nike

所以前几天我在摆弄 CSS 和 float 时偶然发现了一个奇怪的行为(坦率地说,我很惊讶我以前没有遇到过它)。我对它的原因感到困惑(以及为什么我不知道......)。

如果你有一个 div(我们称他为 Bob)并且你试图将他 float 到另一个 div(Jimmy)旁边,它只有在

  1. 吉米也漂浮了
  2. 吉米追在鲍勃后面

所以如果我们有:

<div class="container">
<div id="one">Main Content 1</div>
<div id="two">Sidebar 1</div>
</div>

.container { 
overflow:hidden; /* this essentially clears the floats. You could remove it and add a clearfloat div instead */
margin-bottom:10px;
}
#one {
background-color:red;
margin-right:50px;
}
#two {
width:50px;
float:right;
background-color:blue;
}

我们得到; enter image description here但是如果我们只是交换 #one#two,保持相同的 CSS:

<div class="container">
<div id="two">Sidebar 2</div>
<div id="one">Main Content 2</div>
</div>

我们得到: enter image description here

为什么?我敢肯定它与盒子模型和 float 的定义有关(这让我觉得很愚蠢),但是什么?

你可以摆弄它here

最佳答案

如果你删除 margin-right:50px; 它应该对你更有意义:)

根据定义, block 元素占据父容器的整个宽度。即使你给它一个定义的宽度,那也只是计算宽度的直观表示,不会影响盒子模型。

float 元素正是这样做的,但它 float 在父元素中第一个可用的可 float 空间。在示例一中,它位于第一个 block 元素下方。在示例二中,它位于顶部。

如果您想在示例 1 中实现示例 2 的结果,只需将 float:left; 添加到 #one。

关于html - div 不会 float 在前面的非 float div 旁边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6638155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com