CSS定位
定位(position)用于精确控制元素在页面中的位置,是实现复杂布局的关键技术。
定位类型
| 值 | 说明 | 是否脱离文档流 |
|---|---|---|
static | 默认,正常文档流 | 否 |
relative | 相对定位 | 否 |
absolute | 绝对定位 | 是 |
fixed | 固定定位 | 是 |
sticky | 粘性定位 | 否(滚动时切换) |
相对定位 relative
相对于元素原位置偏移,原空间保留:
CSS
.box {
position: relative;
top: 20px;
left: 30px;
}
/* 常用于:微调位置、作为绝对定位的参照 */
绝对定位 absolute
相对于最近的定位祖先元素定位:
CSS
.parent {
position: relative; /* 建立定位上下文 */
}
.child {
position: absolute;
top: 10px;
right: 10px;
}
/* 居中定位 */
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
固定定位 fixed
相对于视口定位,不随滚动:
CSS
.header {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 1000;
}
.back-to-top {
position: fixed;
bottom: 30px;
right: 30px;
}
粘性定位 sticky
滚动到阈值前为相对定位,之后为固定定位:
CSS
.section-title {
position: sticky;
top: 60px; /* 滚动到距顶部60px时固定 */
}
/* 导航栏吸顶效果 */
.nav {
position: sticky;
top: 0;
z-index: 100;
}
定位偏移属性
CSS
.element {
position: absolute;
top: 10px; /* 距顶部 */
right: 20px; /* 距右侧 */
bottom: 10px; /* 距底部 */
left: 20px; /* 距左侧 */
}
/* 拉伸效果 */
.stretch {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
z-index 层级控制
CSS
.modal {
position: fixed;
z-index: 1000; /* 值越大越在上层 */
}
.overlay {
position: fixed;
z-index: 999;
}
/* 注意:仅定位元素(非static)z-index生效 */
注意:绝对定位元素若找不到定位祖先,则相对于初始包含块(通常是视口)定位。
要点总结
relative相对自身偏移,原空间保留,常作定位参照absolute相对于最近的定位祖先定位,脱离文档流fixed相对于视口定位,适合固定导航、弹窗sticky结合相对与固定定位,适合吸顶导航z-index控制层级,仅对定位元素生效
📝 发现内容有误?点击此处直接编辑