position 属性。它有一大堆的值,名字还都特抽象,别提有多难记了。让我们先一个个的过一遍,包括:static、relative、fixed、absolute 和 sticky。
.static {
position: static;
}
static 是默认值。任意 position: static; 的元素不会被特殊的定位。一个 static 元素表示它不会被 “positioned”,一个 position 属性被设置为其他值的元素表示它会被 “positioned”。
.relative1 {
position: relative;
}
.relative2 {
position: relative;
top: -20px;
left: 20px;
background-color: white;
width: 500px;
}
relative 表现的和 static 一样,除非你添加了一些额外的属性。
在一个相对定位(position 属性的值为 relative)的元素上设置 top、right、bottom 和 left 属性会使其偏离其正常位置。其他的元素的位置则不会受该元素的影响发生位置改变来弥补它偏离后剩下的空隙。
一个固定定位( position 属性的值为 fixed )元素会相对于视窗来定位,这意味着即便页面滚动,它还是会停留在相同的位置。和 relative 一样, top、right、bottom 和 left 属性都可用。
我相信你已经注意到页面右下角的固定定位元素。你现在可以仔细看看它,这里有它所使用的 CSS:
.fixed {
position: fixed;
bottom: 0;
right: 0;
width: 230px;
background-color: white;
}
一个固定定位元素不会保留它原本在页面应有的空隙(脱离文档流)。
令人惊讶地是移动浏览器对 fixed 的支持很差。这里有相应的解决方案。
这是 CSS Fixed 的定位。
</div>absolute 是最棘手的 position 值。 absolute 与 fixed 的表现类似,但是它不是相对于视窗而是相对于最近的 “positioned” 祖先元素。如果绝对定位(position 属性的值为 absolute)的元素没有 “positioned” 祖先元素,那么它是相对于文档的 body 元素,并且它会随着页面滚动而移动。记住一个 “positioned” 元素是指 position 值不是 static 的元素。
这里有一个简单的例子:
.relative {
position: relative;
width: 600px;
height: 400px;
}
.absolute {
position: absolute;
top: 120px;
right: 0;
width: 300px;
height: 200px;
}
这个元素是相对定位的。如果它是 position: static;,那么它的绝对定位子元素会跳过它直接相对于 body 元素定位。
这个元素是绝对定位的。它相对于它的父元素定位。
</div>position:sticky
</div>元素根据正常文档流进行定位,然后相对它的最近滚动祖先(nearest scrolling ancestor)和 containing block (最近块级祖先 nearest block-level ancestor),包括 table-related 元素,基于 top, right, bottom, 和 left 的值进行偏移。偏移值不会影响任何其他元素的位置。
该值总是创建一个新的层叠上下文(stacking context)。注意,一个 sticky 元素会 “固定” 在离它最近的一个拥有“滚动机制”的祖先上(当该祖先的 overflow 是 hidden, scroll, auto, 或 overlay 时),即便这个祖先不是真的滚动祖先。这个阻止了所有“sticky”行为(详情见Github issue on W3C CSSWG):
#sticky {
position: sticky; top: 10px;
width: 450px;
height: 120px;
background: rgba(255,255,255,0.7)
}
/*在 viewport 视口滚动到元素 top 距离小于 10px 之前,
元素为相对定位。之后,元素将固定在与顶部距离 10px 的位置,
直到 viewport 视口回滚到阈值以下。*/
须指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。