说明
绝对定位是元素在移动位置的时候,是相对于它祖先元素来说的。
语法:
选择器 {
position: absolute;
}
绝对定位的特点:
- 如果没有祖先元素或者祖先元素没有定位,则以浏览器为准定位(Document文档)。
示例
没有父亲:top和left都是0
<!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>
.son {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div class="son"></div>
</body>
</html>
展示效果:
没有父亲:top和left都大于0
<!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>
.son {
position: absolute;
top: 100px;
left: 100px;
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div class="son"></div>
</body>
</html>
展示效果:
没有父亲:top和right都大于0
<!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>
.son {
position: absolute;
top: 100px;
right: 100px;
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div class="son"></div>
</body>
</html>
展示效果:
父亲无定位
<!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>
.father {
width: 500px;
height: 500px;
background-color: skyblue;
}
.son {
position: absolute;
top: 0;
right: 0;
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
展示效果: