CSS | 青训营笔记

97 阅读2分钟

这是我参与「第四届青训营 」笔记创作活动的的第2天

CSS Work FLow

  1. 加载并解析HTML -> 加载并解析CSS -> 创建DOM Tree
  2. 在DOM Tree中按照规则给对应元素绑定指定的CSS属性

image.png

  1. 计算CSS中某些属性值
    • resolving阶段只计算当前项目可以得出结果的,例如em->px(只需要使用父元素设置的font-size),相对路径->绝对路径(项目运行路径)
    • formatting阶段会计算需要使用到浏览器实际运行时属性的值,如vh、vw
    • constraining阶段将小数取整

image.png

  1. 获得实际CSS属性

BFC详解

WHAT'S BFC?

Full Name: Block Formatting Context

W3C介绍如下:

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 float isn't none).

  • Absolutely positioned elements (elements where position is absolute or fixed).

  • 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: tabletable-rowtable-row-grouptable-header-grouptable-footer-group (which is the default for HTML tables, table rows, table bodies, table headers, and table footers, respectively), or inline-table.

  • Block elements where overflow has a value other than visible and clip.

  • Flex items (direct children of the element with display: flex or inline-flex) if they are neither flex nor grid nor table containers themselves.

  • Grid items (direct children of the element with display: grid or inline-grid) if they are neither flex nor grid nor table containers themselves.

RULES

  • 盒子在垂直方向依次摆放
  • 盒内垂直 margin 合并
  • BFC 内盒子内的标签不会影响到盒子外
  • BFC 不会和浮动元素重叠
  • 计算 BFC 高度时,浮动元素也参与

APPLICATION

  1. float元素脱离文档流导致的高度坍塌

    解决方法:给浮动元素外层包裹一个BFC

  2. margin collapse

    解决方法:设置padding,或者使用BFC分别包裹相邻元素

  3. 与浮动元素重叠

    解决方法:BFC包裹需要避免被重叠的元素