position
CSS position属性用于指定一个元素在文档中的定位方式。top,right,bottom 和 left 属性则决定了该元素的最终位置。
| 取值 | 是否脱离文档流 | 是否保留元素原位置 | 相对什么位置进行偏移 | 应用 | 备注 |
|---|---|---|---|---|---|
| static | 否 | 是 | 不偏移 | 默认值。位置和布局不变。(正常布局,元素在文档流中当前的布局位置) | 此时 top, right, bottom, left 和 z-index 属性无效。 |
| relative | 是 | 是 | 元素原位置 | 原位置保留。相对元素未添加定位时的位置偏移。 | position:relative 对 table-*-group, table-row, table-column, table-cell, table-caption 元素无效。 |
| absolute | 是 | 否 | 最近的非 static 定位祖先元素(当这样的祖先元素不存在时,则相对于ICB(inital container block, 初始包含块)) | 不保留原位置,做偏移 | 绝对定位的元素可以设置外边距(margins),且不会与其他边距合并。 |
| fixed | 是 | 否 | 屏幕视口(viewport) | 屏幕滚动,元素相对于 viewport 视口仍处于同一位置 | fixed 属性会创建新的层叠上下文。当元素祖先的 transform, perspective 或 filter 属性非 none 时,容器由视口改为该祖先。 |
| sticky | *最近滚动祖先(nearest scrolling ancestor)*和 containing block (最近块级祖先 nearest block-level ancestor) | 元素在跨越特定阈值前为相对定位,之后为固定定位(常用于定位字母列表的头部元素) |
relative(相对定位)
#two {
position: relative;
top: 20px;
left: 20px;
background: blue;
}
absolute(绝对定位)
#three {
position: absolute;
top: 20px;
left: 20px;
}
fixed(固定定位)
#one {
position: fixed;
top: 80px;
left: 10px;
}
sticky(粘性定位)
#one { position: sticky; top: 10px; }