一、相对定位:以自身原本的位置为起点计算偏移量,与其他元素无关,不会影响其他元素
写法格式:position: relative;
<style>
*{
margin: 0;
padding: 0;
}
.parent{
width: 500px;
height: 300px;
border: 1px solid red;
}
.box1{
width: 100px;
height: 100px;
background-color: orange;
/* 相对定位 */
position: relative;
top:320px;
left:100px;
}
.box2{
width: 150px;
height: 150px;
background-color: forestgreen;
}
</style>
<body>
<div class="parent">
<div class="box1">box1</div>
<div class="box2">box2</div>
</div>
</body>
未使用相对定位时:
对box1使用相对定位后;
二、绝对定位:相对于第一个非static定位的父级元素进行定位可以通过top、right、bottom、left 这四个属性来设置元素相对于父级元素位置的偏移量。如果没有满足条件的父级元素,则会相对于浏览器窗口来进行定位。使用绝对定位的元素会对其他元素造成影响。
书写格式:position: absolute;
<style>
*{
margin: 0;
padding: 0;
}
.parent{
width: 500px;
height: 300px;
border: 1px solid red;
}
.box1{
width: 100px;
height: 100px;
background-color: orange;
/* 绝对定位 */
position: absolute;
top: 200px;
left: 200px;
}
.box2{
width: 150px;
height: 150px;
background-color: forestgreen;
}
</style>
<body>
<div class="parent">
<div class="box1">box1</div>
<div class="box2">box2</div>
</div>
</body>
未使用绝对定位之前:
对box1使用绝对定位之后: