这是我参与「第四届青训营 」笔记创作活动的的第2天
CSS Work FLow
- 加载并解析HTML -> 加载并解析CSS -> 创建DOM Tree
- 在DOM Tree中按照规则给对应元素绑定指定的CSS属性
- 计算CSS中某些属性值
- resolving阶段只计算当前项目可以得出结果的,例如em->px(只需要使用父元素设置的font-size),相对路径->绝对路径(项目运行路径)
- formatting阶段会计算需要使用到浏览器实际运行时属性的值,如vh、vw
- constraining阶段将小数取整
- 获得实际CSS属性
BFC详解
WHAT'S BFC?
Full Name: Block Formatting Context
W3C介绍如下:
A block formatting context (BFC) is a part of a visual CSS rendering of a web page. It's the region in which the layout of block boxes occurs and in which floats interact with other elements.
在我看来它就是人为的创造出来的一个isolated region,类似namespace的概念,来实现布局的隔离。
HOW TO CREATE BFC?
以下为W3C介绍的如何创建BFC的方法,我选择了比较常用的一些
-
The root element of the document (
<html>). -
Floats (elements where
floatisn'tnone). -
Absolutely positioned elements (elements where
positionisabsoluteorfixed). -
Inline-blocks (elements with
display: inline-block). -
Table cells (elements with
display: table-cell, which is the default for HTML table cells). -
Anonymous table cells implicitly created by the elements with
display: table,table-row,table-row-group,table-header-group,table-footer-group(which is the default for HTML tables, table rows, table bodies, table headers, and table footers, respectively), orinline-table. -
Block elements where
overflowhas a value other thanvisibleandclip. -
Flex items (direct children of the element with
display: flexorinline-flex) if they are neither flex nor grid nor table containers themselves. -
Grid items (direct children of the element with
display: gridorinline-grid) if they are neither flex nor grid nor table containers themselves.
RULES
- 盒子在垂直方向依次摆放
- 盒内垂直 margin 合并
- BFC 内盒子内的标签不会影响到盒子外
- BFC 不会和浮动元素重叠
- 计算 BFC 高度时,浮动元素也参与
APPLICATION
-
float元素脱离文档流导致的高度坍塌
解决方法:给浮动元素外层包裹一个BFC -
margin collapse
解决方法:设置padding,或者使用BFC分别包裹相邻元素 -
与浮动元素重叠
解决方法:BFC包裹需要避免被重叠的元素