front-end-interview-handbook/packages/quiz/questions/describe-floats-and-how-the.../zh-CN.mdx

34 lines
1.4 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 描述 `float` 及其工作原理。
---
Float 是一个 CSS 定位属性。浮动元素仍然是页面流程的一部分,并将影响其他元素的位置(例如,文本将环绕浮动元素),这与 `position: absolute` 元素不同,后者将从页面流程中移除。
CSS `clear` 属性可用于定位在 `left`/`right`/`both` 浮动元素下方。
如果父元素只包含浮动元素,则其高度将折叠为零。可以通过在容器中浮动元素之后但在容器关闭之前清除浮动来修复它。
## Clearfix hack
`.clearfix` hack 使用巧妙的 CSS [伪元素](/questions/quiz/describe-pseudo-elements-and-discuss-what-they-are-used-for) (`::after`) 来清除浮动。与其在父元素上设置 overflow不如为其应用一个额外的类 `clearfix`。然后应用此 CSS
```css
.clearfix::after {
content: ' ';
visibility: hidden;
display: block;
height: 0;
clear: both;
}
```
或者,给父元素 `overflow: auto` 或 `overflow: hidden` 属性,它将在子元素内建立一个新的块格式化上下文,它将扩展以包含其子元素。
## 琐事
在过去的日子里CSS 框架(如 Bootstrap 2使用 `float` 属性来实现其网格系统。然而,如今有了 CSS Flexbox 和 Grid不再需要使用 `float` 属性。
## 参考
* [Clearfix: A Lesson In Web Development Evolution](https://css-tricks.com/clearfix-a-lesson-in-web-development-evolution/)