CSS:清除:left/right/both; VS 浮动:none;

CSS: Clear:left/right/both; VS Float: none;

我在网站内外检查了几个关于此事的问题,但似乎从未得到明确的定义。

似乎通过实验,float: none; 将元素从浮动布局位置完全删除,并将元素放回常规文档流中。

另一方面,

clear: left/right/both; 似乎打破了元素的浮动,但 并未 将元素放回常规文档流中,而是将元素保留在浮动布局位置流。

这是一个正确的假设吗?是否可以更彻底地解释这个主题,或者引用比单独实验更可靠的来源。

clearing 不会更改元素的 floating 状态 - 它仅定义元素是否允许坐在另一个元素旁边或必须包裹在下面。

The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it.

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

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.

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


以下是您需要 clear 元素的示例:
请注意 footer(非浮动元素)需要在本例中应用清算。

section {float:left; width:60%; height:200px; background:rgba(255,0,0,.3);}
aside {float:right; width:40%; height:100px; background:rgba(0,255,0,.3);}
footer {/*clear:both;*/ background:rgba(0,0,255,.3);}
<section>Main</section>
<aside>Sidebar</aside>
<footer>Footer</footer>


当清理不够时...

所以,您已经成功地浮动了您的元素并突破了 'The Flow',但现在您发现自己有一个 zero-height/collapsing container problem? For that you'll need a clear-fix。这是问题和解决方案的示例:

section {border:1px solid red; padding:10px 5px; clear:both;}
span {display:block; float:left; width:80px; height:80px; margin:0 5px; background:rgba(100,100,100,.3)}

.clearfix {border-color:green;}
.clearfix:after {
  content: "";
  display: table;
  clear: both;
}
<section>
    <span>1</span><span>2</span><span>3</span><span>4</span>
</section>
<section class="clearfix">
    <span>1</span><span>2</span><span>3</span><span>4</span>
</section>