相对定位特点
1相对定位相对于原来的定位
2 占位,不脱标准流
3.标签显示模式特点不变
一般不会独立使用,因为会占位消耗原本布局空间
绝对定位特点
1.脱标,不占位
2. 参照最近定位的父级元素
3.显示模式:绝对定位盒子显示模式为行内块
实现定位居中 绝对定位 如果要求相对于窗口的话 直接改子元素使用绝对定位
1.水平,垂直边偏移50%
{
position:absolute;
left:50%;
top:50%;
}
盒子向上、左平移自身尺寸的一半
.inner {
display: block;
position: absolute;
width: 92px;
height: 32px;
background-color: whitesmoke;
text-align: center;
line-height: 32px;
top: 50%;
left: 50%;
margin-left: -46px;
margin-top: -16px;
}
这里使用margin-left和margin-top将盒子上移自身尺寸的一半
或者使用transfer:
.inner {
display: block;
position: absolute;
width: 92px;
height: 32px;
background-color: whitesmoke;
text-align: center;
line-height: 32px;
top: 50%;
left: 50%;
/* 传统写法 */
/* margin-left: -46px;
margin-top: -16px; */
transform: translate(-50%,-50%);
}
固定定位:position:fixed
1脱标,不占位
2参照物是当前窗口
3 改变显示模式变为行内块
后来者居上
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1 {
position: absolute;
width: 200px;
height: 200px;
background-color: antiquewhite;
z-index: 5;
}
.box2 {
position: absolute;
width: 200px;
height: 200px;
background-color: blue;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>