1、相对定位
格式:position: relative;
相对定位不脱离标准流,仍然在标准流中占有位置,相对定位的移动是相对于在标准流中的位置。
相对定位区分块级元素、行内元素与行内块级元素,即使该元素为相对定位,也不改变元素性质。
当使用相对定位时,一般不使用margin、padding等元素,会影响标准流布局。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>标题</title>
<style>
* {
margin: 0;
padding: 0;
}
.box1 {
height: 200px;
width: 200px;
background-color: red;
left: 120px;
position: relative;
}
.box2 {
height: 200px;
width: 200px;
background-color: blue;
}
.box3 {
height: 200px;
width: 200px;
background-color: yellow;
}
span {
height: 200px;
width: 200px;
background-color: #ccc;
}
</style>
</head>
<body>
<div class="box1"><p>我是块级元素1</p></div>
<div class="box2"><p>我是块级元素2</p></div>
<div class="box3"><p>我是块级元素3</p></div>
<span>我是行内元素</span>
</body>
</html>
2、绝对定位
格式:position: absolution;
绝对定位脱离于标准流,与浮动流类似,绝对定位的移动是根据body标签来做参考的。
绝对定位不区分块级元素、行内元素、行内块级元素。
当祖先标签(父标签、父标签的父标签……)为绝对定位,则该标签默认根据距离自己最近的绝对定位做参考。
绝对定位在以body为参考时,参考的是页面当前大小,而不是以页面整体大小为参考。
绝对定位会忽略祖先元素的内边距。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>标题</title>
<style>
* {
margin: 0;
padding: 0;
}
.box1 {
height: 200px;
width: 200px;
background-color: red;
}
.box2 {
height: 200px;
width: 200px;
background-color: blue;
position: absolute;
top: 30px;
left: 50px;
}
.box3 {
height: 300px;
width: 300px;
background-color: aqua;
position: absolute;
}
.box4 {
height: 100px;
width: 100px;
background-color: darkorange;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
<div class="box3">
<div class="box4"></div>
</div>
</body>
</html>