Fe-interview: [css] 第108天 position的relative和absolute定位原点是哪里?

Created on 1 Aug 2019  ·  5Comments  ·  Source: haizlin/fe-interview

第108天 position的relative和absolute定位原点是哪里?

css

Most helpful comment

简言之,两者的定位原点都是其包含块区域的左上角;只是两种定位元素的包含块有所不同,得出的表明结论就是上述几位所说的。我简单的说一下我对包含块的一些理解:

包含块containing block):用来确定和影响元素的尺寸和位置属性的矩形区域;

The size and position of an element are often impacted by its containing block. Percentage values that are applied to the width, height, padding, margin, and offset properties of an absolutely positioned element (i.e., which has its position set to absolute or fixed) are computed from the element's containing block. ——MDN

一个元素的包含块完全受其position属性值的影响:

  1. staticrelative:最近的块级(display属性值为blockinline-blocklist-item)祖先元素的content-box区域;或者最近的建立格式上下文的祖先元素,比如:table容器,flex容器,grid容器或块级容器。

  2. absolute:最近的非static(fixed, absolute, relative, or sticky)祖先元素的padding-box区域。

  3. fixed:可视窗口viewport本身(属于continuous media类型时)或页面区域page area(属于paged media类型时),即初始包含块

  4. 当属性值为fixedabsolute时,其包含块还有可能是最近的含有transformperspective值不为none的祖先元素的padding-box区域。

html元素的包含块叫做初始包含块initial containing block),它具有可视窗口(用于连续媒体)或页面区域(用于分页媒体)的尺寸

All 5 comments

absolute: 定位原点为第一个position不为static的父级元素的左上角。
可以基于该特性实现height:100%生效
relative:定位原点为元素本身的所在位置。
relative的偏移量设置会导致显示效果和定位原点不重合。

position: relative,它偏移的参照位是其原先在正常文档流中的位置;
position: absolute,它偏移的参照位是父容器的左上角;

单独使用

relative 相对于本身偏移,没有脱离文档流
absolute 相对于浏览器定位,脱离文档流,不占位置

两者一起使用

相对于父元素定位

简言之,两者的定位原点都是其包含块区域的左上角;只是两种定位元素的包含块有所不同,得出的表明结论就是上述几位所说的。我简单的说一下我对包含块的一些理解:

包含块containing block):用来确定和影响元素的尺寸和位置属性的矩形区域;

The size and position of an element are often impacted by its containing block. Percentage values that are applied to the width, height, padding, margin, and offset properties of an absolutely positioned element (i.e., which has its position set to absolute or fixed) are computed from the element's containing block. ——MDN

一个元素的包含块完全受其position属性值的影响:

  1. staticrelative:最近的块级(display属性值为blockinline-blocklist-item)祖先元素的content-box区域;或者最近的建立格式上下文的祖先元素,比如:table容器,flex容器,grid容器或块级容器。

  2. absolute:最近的非static(fixed, absolute, relative, or sticky)祖先元素的padding-box区域。

  3. fixed:可视窗口viewport本身(属于continuous media类型时)或页面区域page area(属于paged media类型时),即初始包含块

  4. 当属性值为fixedabsolute时,其包含块还有可能是最近的含有transformperspective值不为none的祖先元素的padding-box区域。

html元素的包含块叫做初始包含块initial containing block),它具有可视窗口(用于连续媒体)或页面区域(用于分页媒体)的尺寸

  • relative: static情况下的原点
  • absolute: 定位不为static父级的原点,若没有的话,相对于窗口;
Was this page helpful?
0 / 5 - 0 ratings