CSS 定位
warning:
这篇文章距离上次修改已过192天,其中的内容可能已经有所变动。
CSS 定位可以通过 position
属性来实现,它有以下几个值:
static
:默认值,没有定位。relative
:相对于元素在文档流中的原始位置进行定位。absolute
:相对于最近的非static
定位的父元素进行定位。fixed
:相对于浏览器窗口进行定位。sticky
:基于用户的滚动位置相对定位。
实例代码:
/* 相对定位 */
.relative {
position: relative;
top: 10px; /* 向下移动 10px */
left: 20px; /* 向右移动 20px */
}
/* 绝对定位 */
.absolute {
position: absolute;
top: 50px; /* 相对于最近的非 static 定位父元素向下移动 50px */
right: 30px; /* 向右移动 30px */
}
/* 固定定位 */
.fixed {
position: fixed;
bottom: 0; /* 固定在底部 */
left: 0; /* 固定在左边 */
}
/* 粘性定位 */
.sticky {
position: sticky;
top: 0; /* 当向下滚动超过其父元素时,粘性定位变为固定定位 */
}
使用时,只需将相应的类添加到 HTML 元素上即可实现不同的定位效果。
评论已关闭