css中的position属性用于设置元素位置的确定方式,它有以下几种取值:
- static:默认定位方式,子元素在父容器中挨个摆放
- absolute:绝对定位,元素不占据父容器空间,相当于文档body定位 (如果元素的父级节点中有position不等于static的,则相当于最近的非static父节点定位)
- relative:相对定位,占据父容器空间,但显示位置相当于自身位置进行偏移
- fixed:固定定位,元素相当于窗口进行定位 (相当于窗口而不是文档定位,所以即使发生进度条滚动时,元素相当于窗口的位置仍然不变)
- sticky:粘性定位,这是一个带过渡效果的定位方式,只有在滚动时才能看出其变化效果 当偏移量大于指定值时,以static方式显示 当偏移量小于指定值时,以fixed方式显示,但却像relative方式一样占据父容器空间 当元素到达父容器边缘时,位置相当于父容器不再变化
下面以代码来展示实际运行效果: html代码:
div1
div2
div3
static定位
#div1 {
width: 200px;
height: 100px;
background: red;
position: static;
}
#div2 {
width: 200px;
height: 100px;
background: yellow;
}
#div3 {
width: 200px;
height: 100px;
background: blue;
}
absolute定位
#div1 {
width: 200px;
height: 100px;
background: red;
position: absolute;
left: 400px;
top: 300px;
}
relative定位
#div1 {
width: 200px;
height: 100px;
background: red;
position: relative;
left: 400px;
top: 300px;
}
fixed定位
#div1 {
width: 200px;
height: 100px;
background: red;
position: fixed;
right: 10px;
bottom: 10px;
}
sticky定位
* {
margin: 0px;
padding: 0px;
}
#div1 {
width: 400px;
height: 400px;
background: red;
}
#div2 {
width: 200px;
height: 100px;
background: yellow;
position: sticky;
top: 40px;
}
#div3 {
width: 300px;
height: 200px;
background: rebeccapurple;
}
#div4 {
width: 400px;
height: 200px;
background: lightblue;
}
#div5 {
width: 400px;
height: 2000px;
background: lightblue;
}