position属性的五种定位
position属性
- static(静态定位)
- relative(相对定位)
- absolute(绝对定位)
- fixed(固定定位)
- sticky(粘性定位)
1. 静态定位(static)(默认)
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.father {
width: 500px;
height: 500px;
border: 5px solid palevioletred;
margin: 100px auto 0;
}
.son {
position: static;
/*此处给了top和left值*/
top: 50%;
left: 50%;
/*静态页面 top/left/right/bottom 属性均不生效*/
width: 200px;
height: 200px;
border: 5px solid paleturquoise;
}
<div class="father">
静态定位(父级)
<div class="son">
(子级)
</div>
</div>
- position: static; 的元素不会以任何特殊方式定位;它始终根据页面的正常流进行定位(不使用)。
2. 相对定位(relative)
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.father {
width: 500px;
height: 500px;
border: 5px solid palevioletred;
margin: 100px auto 0;
}
.son1 {
/*相对定位:相对于其正常位置进行定位*/
position: relative;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
border: 5px solid paleturquoise;
}
.son2 {
width: 200px;
height: 200px;
border: 5px solid plum;
}
}
<div class="father">
静态定位(父级)
<div class="son">
(子级)
</div>
</div>
- 相对定位移动后保留原先位置。
3. 绝对定位(absolute)(子绝父相)
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.father {
/*使用绝对定位时,父级必须添加相对定位*/
position: relative;
width: 500px;
height: 500px;
border: 5px solid palevioletred;
margin: 100px auto 0;
}
.son1 {
/*绝对定位:相对于其父级位置进行定位*/
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
border: 5px solid paleturquoise;
}
.son2 {
width: 200px;
height: 200px;
border: 5px solid plum;
}
<div class="father">
绝对定位(父级)
<div class="son1">
(子级1)
</div>
<div class="son2">
(子级2)
</div>
</div>
- 绝对定位移动后不保留原先位置。
4. 固定定位(fixed)
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.father {
width: 500px;
height: 500px;
border: 5px solid palevioletred;
margin: 100px auto 0;
}
.son1 {
/*固定定位:相对于视口进行定位*/
position: fixed;
top: 100px;
left: 100px;
width: 200px;
height: 100px;
border: 5px solid paleturquoise;
}
.son2 {
width: 200px;
height: 200px;
border: 5px solid plum;
}
<div class="father">
固定定位(父级)
<div class="son1">
(子级1)
</div>
<div class="son2">
(子级2)
</div>
</div>
- 固定定位移动后不保留原先位置。
5. 粘性定位(sticky)
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.father {
width: 500px;
height: 1500px;
border: 5px solid palevioletred;
margin: 100px auto 0;
}
.son1 {
/*粘性定位:相对于视口进行定位*/
position: sticky;
top: 0;
left: 0;
width: 200px;
height: 100px;
border: 5px solid paleturquoise;
}
.son2 {
width: 200px;
height: 200px;
border: 5px solid plum;
}
<div class="father">
粘性定位(父级)
<div class="son1">
(子级1)
</div>
<div class="son2">
(子级2)
</div>
</div>
-
页面滑动前
-
页面滑动后
-
粘性定位移动后不保留原先位置。
(定位数值为百分比时,是父级宽高的百分比)