定位
position 属性
top/bottom/left/right 属性
- 定位偏移属性;
- 见 [[040-类型-变量]];
positioned {
position: absolute;
top: 40px;
left: 40px;
}
定位样式
- position: 选择定位方案;
positioned {
position: static;
position: relative;
position: absolute;
position: fixed;
position: sticky;
}
static positioning
- static: normal flow 默认定位;
- top/right/bottom/left/z-index 无效;
positioned {
position: static;
background: yellow;
}
relative positioning
- relative: 保留 normal flow 位置;
- top/bottom/left/right 基于原位置偏移;
positioned {
position: relative;
background: yellow;
}
absolute positioning
- absolute: 脱离 normal flow;
- 根据 containing block 定位;
positioned {
position: absolute;
background: yellow;
}
fixed positioning
- fixed: 通常基于 viewport 定位;
positioned {
position: fixed;
background: yellow;
}
sticky positioning
sticky positioning
- sticky 属性;
- relative 和 fixed 的混合定位;
- 默认按 relative 参与布局;
- 滚动到阈值后按 fixed 方式吸附;
positioned {
position: sticky;
background: yellow;
}
scrolling index 机制
- 多个 sticky 元素按文档顺序层叠覆盖;
失效问题
- 父元素高度必须大于子元素;
- 父元素 overflow 避免设置为 hidden 或 auto;
positioning context
containing block
- static: normal flow 布局, 不创建 absolute containing block;
- relative: normal flow 布局后相对自身原位置偏移, 可创建 absolute containing block;
- sticky: normal flow 布局后受最近 scroll container 约束, 可创建 absolute containing block;
- absolute;
- 最近的 positioned ancestor;
- 或可创建 containing block 的祖先;
- fixed:
- 通常相对 viewport;
- transform/filter/perspective/contain 等祖先可创建 containing block;
initial containing block
- 尺寸等于 viewport;
- 包含 html 标签;
创建 positioning context
- position 值非 static 即可;
- 推荐使用 relative;
.positioned {
position: relative;
}
z-index
- z-index: 设置元素 stack level;
- z-index 值越大, stack level 越高;
- 元素重叠时, stack level 高者优先显示;
dashed-box {
position: relative;
z-index: 1;
}