position:
1、静态定位 static
2、相对定位 relative
3、固定定位 fixed
4、绝对定位 absolute
left: 10px (%) 当前定位元素相对于参考物左边界的距离
right: 10px (%) 当前定位元素相对于参考物右边界的距离
top: 10px (%) 当前定位元素相对于参考物上边界的距离
bottom: 10px (%) 当前定位元素相对于参考物下边界的距离
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
div {
width: 200px;
height: 200px;
color: salmon;
font-size: 30px;
line-height: 200px;
text-align: center;
}
.static {
position: static;
background-color: #ecbe34;
left: 0;
top: 0;
}
.relative {
position: relative;
background-color: #4c8ced;
left: 0;
top: 0;
}
.fixed {
position: fixed;
background-color: #6cb254;
left: 0;
top: 0;
}
.absolute {
position: absolute;
background-color: #ff6700;
left: 0;
top: 0;
}
.father{
width: 500px;
height: 500px;
background-color: purple;
margin: 100px;
}
</style>
</head>
<body>
<div class="father" >
<div class="static">静态定位</div>
<div class="relative">相对定位</div>
<div class="fixed">固定定位</div>
<div class="absolute">绝对定位</div>
</div>
</body>
</html>
静态定位:默认为静态定位,以父元素为对象,没有定位,元素出现在正常的流中
相对定位:以自己最初位置作参考, 没有脱标只是移动,用来微调元素
固定定位:以浏览器窗口左上角作为参考 能动 不保留原来的位置--> 脱标
绝对定位:脱标 离它最近的拥有定位属性的元素作为参考 不保留原来位置
注意: 父亲没有定位的时候,子决父异 父亲已有定位,就不用管了
定位居中(需脱标)
left:50%
top:50%
margin-left: - width/2;
margin-top: - height/2;
图层管理(只有绝对定位才有层级)
层级 z-index:n + 提高 - 降低
绝对定位的元素 层级被提高 高于标准流
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
width: 200px;
height: 200px;
float: left;
}
/*层级 z-index:n + 提高 - 降低
只有绝对定位才有层级 */
.red{
background-color: red;
}
.blue{
/*绝对定位的元素 层级被提高 高于标准流*/
background-color: blue;
position: absolute;
left: 30px;
top: 30px;
z-index: -1;
}
.yellow{
/*同为绝对定位 层级高于蓝色*/
background-color: yellow;
position: absolute;
left: 60px;
top: 60px;
z-index: -1;
}
</style>
</head>
<body>
<div class="red"></div>
<div class="blue"></div>
<div class="yellow"></div>
</body>
</html>