前言
前面一篇博客,我们提到了相对定位。除了相对定位,我们还有一个绝对定位。下面分享我学习到的绝对定位。
绝对定位
绝对定位使用的是position: absolute;
定位需要一个参照物:根据谁来做这个定位的?
查找参照物顺序:先找父级元素,如果有定位属性(positon
)就以这个元素作为参照物发生偏移。如果没有找到就向外层逐一查找,直到找到positon
属性的元素,如果一直都没有,那么就以最外层html元素作为参照物发生偏移。
代码实例
只要复制下面的代码,就可以看到绝对定位的效果。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.box1{
width: 600px;
height: 400px;
margin: 100px auto;
background-color: gray;
border: 1px solid gray;
position: relative;
}
.box2{
width: 400px;
height: 200px;
margin: 50px auto;
background-color: green;
}
.box3{
width: 100px;
height: 100px;
background: red;
border-radius: 50%;
/*绝对定位 参照物是有定位属性的最近的父级元素*/
position: absolute;
right: 0;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2">
<div class="box3">
</div>
</div>
</div>
</body>
</html>