浮动与清除浮动
float 如何让元素浮动?
- float: 让元素脱离常规流, 并向 inline 方向浮动;
section {
float: none;
float: left;
float: right;
float: inline-start;
float: inline-end;
}
float 与常规流是什么关系?
- 浮动元素与常规流分离;
- 浮动元素位于常规流层级之上;
- 浮动影响常规流的 content box, 但不影响其 padding 与 margin box;
浮动会带来什么问题?
- 浮动的子元素脱离常规流, 父元素高度无法包住它;
- 表现: 父容器高度塌陷, 背景/边框包不住浮动内容;

如何清除浮动?
- 思路一: 用
clear把元素下移到浮动元素底部; - 思路二: 让父元素创建 BFC;
.left {
clear: none;
clear: left; /* 左侧浮动元素底部 */
clear: right; /* 右侧浮动元素底部 */
clear: both; /* 两侧底部 */
}
- clearfix hack:
::after生成空子元素,display: block+clear: both撑开父元素;
.wrapper::after {
content: "";
clear: both;
display: block;
}
- 创建 BFC:
overflow: auto(非 visible) 或display: flow-root;