CSS 之 position详解

position 有五个值:static、relative、absolute、fixed、inherit。

static

是默认值。就是按正常的布局流从上到下从左到右布局,平常我们做网页时,没有指定 position,也就表示使用 static。

relative

没有脱离布局流,此时可以使用 top、right、bottom、left 属性。

  • top 和 bottom 共存时,使用 top 值,忽略 bottom 值;
  • left 和 right 共存时,使用 left 值,忽略 right 值;

relative 是相对位置,指相对于元素的 position 为 static 时的位置:

  • top 相对于 static 下移多少像素(若 top 是负值,则上移)。
  • right 相对于 static 左移多少像素(若 right 是负值,则右移)。
  • bottom 相对于 static 上移多少像素(若 bottom 是负值,则下移)。
  • left 相对于 static 右移多少像素(若 left 是负值,则左移)。

使用 relative 之后:

  • 原来的空间不会被其他元素挤占。
  • 元素在最终位置时也不会挤占其他元素的空间,它浮动到其它元素的上方。

absolute

脱离布局流,此时可以使用 top、right、bottom、left,但这些属性不再是相对于 static 时的位置,而是相对于 containing block 的,相对于其边框内边缘的,而不是其 padding 内边缘。也就是相对于最近的 position不是static的块级祖先元素盒子进行定位。

使用 absolute 之后:

  • 原来的空间会被其他元素挤占。
  • 元素在最终位置时也不会挤占其他元素的空间,它浮动到其它元素的上方。

fixed

它的模式与 absolute 相同,不过无论怎么拖动滚动条,它始终固定在屏幕的指定位置。在 IE6 中不支持这个属性;在 IE7 中支持这个属性但需要指明 DOCTYPE;Firefox 等浏览器支持这个属性。

top、right、bottom、left 属性指相对于视口的。

inherit

继续父元素的 position 值。

如何确定包含块:

确定包含块的过程完全依赖于这个包含块的 position 属性:

  1. 如果 position 属性是 static 或 relative 的话,包含块就是由它的最近的祖先块元素(比如说inline-block, block 或 list-item元素)或格式化上下文(比如说 a table container, flex container, grid container, or the block container itself)的内容区的边缘组成的。
  2. 如果 position 属性是 absolute 的话,包含块就是由它的最近的 position 的值不是 static (fixedabsoluterelative, or sticky)的祖先元素的内边距区的边缘组成的。
  3. 如果 position 属性是 fixed 的话,包含块就是由 viewport (in the case of continuous media) or the page area (in  the case of paged media) 组成的。
  4. 如果 position 属性是 absolute 或 fixed,包含块也可能是由满足以下条件的最近父级元素的内边距区的边缘组成的:
    1. transform or perspective value other than none
    2. will-change value of transform or perspective
    3. filter value other than none or a will-change value of filter (only works on Firefox).

注意: 根元素(<html>)所在的包含块是一个被称为初始包含块的矩形。It has the dimensions of the viewport (for continuous media) or the page area (for paged media).

 

由包含块计算百分值

如上所述,如果某些属性被赋予一个百分值的话,它的计算值是由这个元素的包含块计算而来的。这些属性包括盒模型属性和偏移属性:

  1. height, top, bottom 这些属性由包含块的 height 属性的值来计算它的百分值。如果包含块的 height 值依赖于它的内容,且包含块的 position 属性的值被赋予 relative 或 static的话,这些值的计算值为0。
  2. width, left, right, padding, margin这些属性由包含块的 width 属性的值来计算它的百分值。

 

原文地址:https://www.cnblogs.com/linusflow/p/9037916.html