css - 具有清除 :both has floating sibling elements on both sides of it 的元素

标签 css css-float

我的理解是一个带有 clear:both; 的 div;不会在其两侧放置任何 float 兄弟 div。在这个例子中,我有 3 个兄弟,在一个容器 div 内留下 float div,带有溢出:auto。有足够的空间让他们所有人并排。

链接到下面的 jsfiddle。

当我将 clear:both 应用到中间 div 时,它会将其移动到下一行(如预期的那样),但是它右侧的 div 也会向下移动并保持在其右侧,尽管该区域已被清除。我希望每个 div 都在一个新行上。

enter image description here

更进一步,如果我只是添加 clear:right;到中间的 div 它仍然在原处(与左侧的 div 一致 - 正如预期的那样),右侧的 div 也留在它旁边。我会虽然正确的 div 会移动到新行。

enter image description here

这种行为似乎与 clear 应该通过防止 float 兄弟元素彼此相邻来实现的目的相矛盾。谁能解释一下?

jsfiddle在这里:https://jsfiddle.net/2tfgwmek/1/

HTML

 <div class="container">
    <div class="left">Left Div<br>float: left; </div>
    <div class="middle">Middle Div<br>float: left; clear:both; </div>
    <div class="right">Right Div<br> float:left </div>
 </div>

CSS
.container {
   width:300px;
   overflow:auto;
   border:solid 2px black;
}

.container > div {
   width:90px; height:90px;
   border:solid 1px red;
   background:grey;
   float:left;
   color:white;
}

.middle {
   clear:both;
}

最佳答案

clear仅适用于您已应用的元素之前的元素 clear到。

https://developer.mozilla.org/en-US/docs/Web/CSS/clear

The clear CSS property specifies whether an element can be next to floating elements that precede it or must be moved down (cleared) below them. The clear property applies to both floating and non-floating elements.



leftright (或 both )值是指前一个元素上 float 的方向。所以在这里,您可以在中间 div 上清除的唯一 float 是它之前的那个,并且该元素向左浮动,所以 clear: left是你可以使用的所有会影响布局的东西。 clear: right在您的示例中不会做任何事情。

如果中间的 div 之前有 2 个 div,一个向左浮动,另一个向右浮动,那么您可以使用 clear: leftclear: right (或 clear: both )影响布局。

关于css - 具有清除 :both has floating sibling elements on both sides of it 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42989447/

相关文章:

javascript - 将菜单修复为响应式菜单 .. css/jquery

html - 如何只给无序列表中的元素符号上色

css - 更改轮播背景的亮度( Bootstrap )

html - 在 3 列显示中叠瓦式 float

html - 这是设置媒体查询的有效且正确的方法吗?

javascript - 使用 jquery 旋转后其他元素的不当行为

html - float 在div上不起作用

html - divs网格在IE7中显示不正确

CSS 布局问题、 float 、嵌套 div

html - float 元素下的额外边距