/**
@date 2022-07-31
@description 你可能不知道的 position
*/
壹(序)
日常工作中 position 出现得真的很频繁,作为 CSS 中的重要属性,从我工作以来听到的 CSS 代码规范中一定有一条是:保证 position 放在第一行;
这无疑是对 position 地位的肯定,但是实话实说,之前对于 position 的理解真的很浅显;
比如:
认为 fixed 一定是基于 viewport;
不了解 sticky 的正确使用方式;
没有完全理解 absolute 和 fixed;
所以对 position 做一个小结。
贰(简介)
先简单介绍一下 position;
position 是一种 CSS 属性,用于定义当前 Element 在 Dom 中的定位方式;
有以下定位类型:static、relative、absolute、fixed、sticky;
通过 top、right、bottom、left 来决定 Element 的位置;
叁(static)
position 默认为 static,static 不会脱离文档流,就是 Element 正常的布局,所以 top、right、bottom、left 无效;
肆(relative)
relative 不会脱离文档流,所以设置 top 等之后也会在原位置留下空白,并且滚动也是基于祖先元素的滚动;
所以一般说相对定位是相对于元素本身进行定位;
肆(absolute)
absolute 会脱离文档流,那么绝对定位的元素之前的位置就会空出来,被后面的元素顶上,绝对定位的元素就会覆盖在后面的元素上面;
很多人认为 absolute 基于最近的 position 不为 static 的祖先元素进行偏移,没有的话就基于 root 元素;
但事实并非如此,我们都知道 CSS 中有个概念叫 包含块(containing block),它能影响元素的 size 以及 position 属性,而 absolute 与 fixed 元素的包含块还有以下情况:
form MDN Identifying the containing block:
If the
positionproperty isabsoluteorfixed, the containing block may also be formed by the edge of the padding box of the nearest ancestor element that has the following:
- A
transformorperspectivevalue other thannone- A
will-changevalue oftransformorperspective- A
filtervalue other thannoneor awill-changevalue offilter(only works on Firefox)- A
containvalue ofpaint(e.g.contain: paint;)- A
backdrop-filterother thannone(e.g.backdrop-filter: blur(10px);)
还有一点,absolute 元素的滚动是根据它的偏移基于的祖先元素,有点绕,举个例子就是:
如果 content 基于 wrapper 定位,则根据 wrapper 滚动;
如果 content 基于 root 定位,则根据 root 滚动;
肆(fixed)
fixed 会脱离文档流,设置了 top 等值后就固定在某个地方了;
fixed 的元素是基于最近的 transform、perspective、filter 属性为非 none 的祖先元素,没有符合条件的祖先元素则基于 viewport;
absolute 里面说到了 containing block,对 fixed 的影响一样,滚动也和 absolute 的表现一样,这里不做赘述;
肆(sticky)
sticky 还是在正常文档流里面,只是在滚动的时候,会 “粘” 在最近的 overflow 为 auto、overlay、hidden、scroll 的祖先元素上,如果没有任何祖先元素满足此条件,则基于 root 元素;
使用 sticky 时,如果发现与想要的结果不一致,可以去看看是不是想要 sticks 的元素的子元素设置了 overflow,导致 sticks 的元素和预期不符
肆(总结)
写了一个简单的 demo 来好好的理了一下 position 的使用,主要是以下几点需要注意:
- fixed 与 absolute 元素在浏览器上面的表现可能并不是像大部分资料说的那样
- fixed 与 absolute 元素的滚动
- 使用 sticky 时需要注意哪些祖先元素设置了 overflow