CSS中的position属性
CSS中的position属性经常用到一共有一下几种:
position: relative; /* 相对定位 */
position: absolute; /* 绝对定位 */
position: fixed; /* 固定定位 */
position: sticky; /* 粘性定位 */
相对定位
相对定位:元素相对于自己原来的位置进行调整(原来的位置仍然保留)
用途
- 子绝父相
- 等等
取值(可以为负值)
- left:右移
- right:左移
- top:下移
- bottom:上移
.item{
background-color: #328898;
position: relative;
top: 80px;
left: 60px;
}

绝对定位
绝对定位:元素的位置相对于最近的已定位父元素,如果元素没有已定位的父元素,那么它的位置相对于<html>
绝对定位脱离了标准文档流,失去原来的位置;所以绝对定位不遵守标准文档流的性质,标签的行内元素、块级元素没有效果了
取值
- left:右移
- right:左移
- top/bottom:下移
- bottom:上移
父元素没有定位
.item{
/* 父元素没有定位 */
background-color: #328898;
position: absolute;
top: 80px;
left: 60px;
}

父元素有定位
<div class="item one">
<div class="item two"></div>
</div>
.one {
background-color: #455053;
position: relative;
}
.two {
/* 父元素相对定位 */
background-color: #328898;
position: absolute;
top: 90px;
left: 90px;
}

注意
如果绝对定位中的父元素出现已经定位,包括绝对定位、相对定位、固定定位、粘性定位,将以最近父元素为参考点进行定位;
绝对定位剧中小技巧
绝对定位后使用transform: translate(-50%, -50%);使其位移实现局中
<div class="item one">
<div class="item two"></div>
</div>
.one {
background-color: #455053;
position: relative;
}
.two {
width: 80px;
height: 60px;
background-color: #328898;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

固定定位
固定定位:元素相对与浏览器窗口进行固定位置
取值
- left:右移
- right:左移
- top/bottom:下移
- bottom:上移
.five{
width: 50px;
height: 50px;
background-color: #eb4493;
position: fixed;
top: 100px;
left: 100px;
}

粘性定位
粘性定位:粘性定位的元素是依赖于用户的滚动,在 position:relative 与 position:fixed 定位之间切换。元素定位表现为在达到特定阈值前为相对定位,之后为固定定位。这个特定阈值指的是 top, right, bottom 或 left 之一,换言之,指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。应用最多的为吸顶特效
.two {
width: 150px;
height: 200px;
background-color: #328898;
position: sticky;
top: 0;
}

结尾
以上position常用属性,如有错误请在评论区留言
本文详细介绍了CSS中的position属性,包括relative(相对定位)、absolute(绝对定位)、fixed(固定定位)和sticky(粘性定位)。相对定位保持元素原有位置并调整,绝对定位相对于最近已定位父元素定位,固定定位相对于浏览器窗口定位,粘性定位在特定阈值前为相对定位,之后变为固定定位。文中还提供了各种定位的示例和使用技巧,如利用transform实现居中等。
447

被折叠的 条评论
为什么被折叠?



