元素设置了position属性:
div{
/* 静态定位 默认值 */
position: static;
/* 相对定位 */
position: relative;
/* 绝对定位 */
position: absolute;
/* 固定定位 */
position: fixed;
/* 粘性定位 */
position: static;
}
1、相对定位
相对盒子原来的位置偏移,原本所占空间不变,没有脱离文档流,一般用来做绝对定位的父元素。
2、绝对定位
- 当浮动元素被设置为绝对定位,元素的float属性会失效
- 相对于设置了定位属性(除static)的父元素偏移
- 如果没有就相对于html元素偏移
- 脱离了文档流,不再占据空间
- 子绝父相
子元素设置为绝对定位,父元素设置为相对定位,父元素位置发生变化,子元素跟着变化。
-
使用z-index可以改变堆叠顺序,数值越大,堆叠在越上方
具体效果可看如下代码:
<div class="box">
<a href="" class="nav1">导航1</a>
<section></section>
<a href="" class="nav2">导航2</a>
<section></section>
<a href="" class="nav3">导航3</a>
<section></section>
<a href="" class="nav4">导航4</a>
<section></section>
<a href="" class="nav5">导航5</a>
<section></section>
</div>
* {
padding: 0;
margin: 0;
}
.box {
width: 550px;
height: 500px;
border: 1px solid;
position: relative;
left: 50px;
top: 50px;
}
a {
display: inline-block;
width: 50px;
height: 30px;
background-color: gray;
text-align: center;
line-height: 30px;
position: absolute;
}
section {
width: 550px;
height: 400px;
position: absolute;
top: 100px;
}
.nav1 {
left: 50px;
}
.nav1:hover+section {
background-color: hotpink;
z-index: 5;
}
.nav2 {
left: 150px;
}
.nav2:hover+section {
background-color: rgb(255, 220, 105);
z-index: 4;
}
.nav3 {
left: 250px;
}
.nav3+section {
background-color: rgb(105, 255, 105);
z-index: 3;
}
.nav4 {
left: 350px;
}
.nav4:hover+section {
background-color: rgb(105, 213, 255);
z-index: 2;
}
.nav5 {
left: 450px;
}
.nav5:hover+section {
background-color: rgb(255, 105, 230);
z-index: 1;
}
a:hover+section {
z-index: 6;
transition: all linear 2s;
}
/* 拓展:transition: all linear 2s
表示图片的变化,属性值分别指变化的范围、变化的方式及变化的时间 */
4、固定定位
相对于浏览器窗口的固定位置,不会随着用户的滚动变化,脱离文档流
5、粘性定位
依赖于用户的滚动,在相对定位与固定定位之间切换,指定top、left、right、bottom四个阈值其中之一,粘性才会生效。(一般用于页面导航的吸顶效果)