绝对定位

包含块和绝对定位元素

元素绝对定位时,会完全从文档流删除,然后相对于其包含块定位,其边界根据偏移属性(left,top等)放置。

对于一个非根元素,如果其position为absolute,包含块为最近的position不是static的祖先元素。如果这个祖先元素是块级元素,包含块则设置为该元素的内边距边界;如果这个祖先是行内元素,包含块则设置为该祖先元素的内容边界。

自动边偏移

元素绝对定位时,如果除了bottom外某个偏移属性设置为auto,会有特殊的行为。

原文:

when we consider the effect of positioning, it quickly becones clear that authors can do a great deal of damage to layout, just as they can do very interesting things. [4] This is usually the case with useful technologies: the sword always has at least two edges, both of them sharp.

设置'[4]'为绝对定位,'top=0 left=0',效果如下:

when we consider the effect of positioning, it quickly becones clear that authors can do a great deal of damage to layout, just as they can do very interesting things. [4] This is usually the case with useful technologies: the sword always has at least two edges, both of them sharp.

把它的top改为auto:

when we consider the effect of positioning, it quickly becones clear that authors can do a great deal of damage to layout, just as they can do very interesting things. [4] This is usually the case with useful technologies: the sword always has at least two edges, both of them sharp.

可以看到,绝对定位元素的top设置为auto与设置为0的表现是不一样的。设置为auto后,绝对定位元素的 顶端相对于其静态位置对齐。其中静态位置指它未定位前在正常流中的位置。

如果left或right为auto呢,也适用上述规则。这种情况下,定位元素的左(或右)边界与元素未定位时该边界原本的位置对齐。修改上述例子,使top和left都为auto。

when we consider the effect of positioning, it quickly becones clear that authors can do a great deal of damage to layout, just as they can do very interesting things. [4] This is usually the case with useful technologies: the sword always has at least two edges, both of them sharp.

非替换元素的放置和大小

对于定位的非替换元素的宽度和水平放置,这里有一条规则: left + margin-left + border-left-width + padding-left + width + padding-right + border-right-width + margin-right + right = 包含块的width

对于定位的非替换元素的高度和垂直放置,规则与水平规则一样。

原文

An absolutely positioned element can have its content shirink-wrapped thanks to the way positioning rules work.

如果left,right,width都为auto

如果left,right,width都为auto,就会得到上节的结果:左边界置于其静态位置。

下例,left,width,right为auto,top为0

An absolutely positioned element can have its content shirink-wrapped thanks to the way positioning rules work.

如果left,right,width都不为auto,左右边距为auto

如果left,right,width都不为auto,左右边距为auto,此时左右边距会设置成相等的值,使元素水平居中。

An absolutely positioned element can have its content shirink-wrapped thanks to the way positioning rules work.

如果left,right,width,margin-left,margin-right都不为auto

如果left,right,width,margin-left,margin-right都不为auto,此时就会出现过度受限的情况。 此时用户代理会修改right的值,或者忽略right值。

An absolutely positioned element can have its content shirink-wrapped thanks to the way positioning rules work.

只要有一个水平属性为auto,用户代理就会修改这个auto来适应规则

把上述例子的margin-left设置为auto

An absolutely positioned element can have its content shirink-wrapped thanks to the way positioning rules work.

替换元素的位置和大小

替换元素与非替换元素在绝对定位上的规则基本相同。