定位模式通过CSS的position来设置:
值 | 语义 |
static | 静态定位(无定位) |
relative | 相对定位(相对自身原来的位置) |
absolute | 绝对定位(相对于祖先元素) |
fixed | 固定定位 |
相对定位的盒子偏移后,仍然保留其原来的位置,后面的盒子不会浮上来占据其位置(不脱标);绝对定位的盒子偏移后,不保留其原来的位置,后面的盒子后浮上来占据其位置。
盒子具体移动的距离通过CSS的边偏移来设置,例如top: 100px,盒子的顶端距离其父级元素上边线100px;left: 50px,盒子的左端距离其父级元素左边线50px。
1.position: relative
相对自身原来位置移动,且保留自己原来的位置,不会影响后面的盒子(不脱标)。
2.position: absolute
相对于祖级元素,若没有祖先元素或祖先元素没有定位,则以浏览器文档为准。
总而言之,绝对定位的盒子在找移动参照时,一层层往上找有定位的祖先元素,若有该祖先元素存在,就以该元素为准,如果没有祖先元素或者祖先元素都没有定位,则以浏览器为准。
例如:
father有定位,son以father为准:
<!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>
.grandfather {
position: relative;
top: 100px;
left: 0px;
width: 800px;
height: 800px;
background-color: Thistle;
}
.father {
position: absolute;
top: 100px;
left: 0px;
width: 500px;
height: 500px;
background-color: LightSkyBlue;
}
.son {
position: absolute;
bottom: 0px;
right: 10px;
width: 200px;
height: 200px;
background-color: tomato;
}
</style>
</head>
<body>
<div class="grandfather">
grandfather
<div class="father">
father
<div class="son">
son
</div>
</div>
</div>
</body>
</html>
father没有定位,grandfather有定位,son以grandfather为准:
<!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>
.grandfather {
position: relative;
top: 100px;
left: 0px;
width: 800px;
height: 800px;
background-color: Thistle;
}
.father {
/* position: absolute;
top: 100px;
left: 0px;*/
width: 500px;
height: 500px;
background-color: LightSkyBlue;
}
.son {
position: absolute;
bottom: 0px;
right: 10px;
width: 200px;
height: 200px;
background-color: tomato;
}
</style>
</head>
<body>
<div class="grandfather">
grandfather
<div class="father">
father
<div class="son">
son
</div>
</div>
</div>
</body>
</html>
son的祖先元素都没有定位,son以浏览器为准:
<!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>
.grandfather {
/* position: relative;
top: 100px;
left: 0px;*/
width: 800px;
height: 800px;
background-color: Thistle;
}
.father {
/* position: absolute;
top: 100px;
left: 0px;*/
width: 500px;
height: 500px;
background-color: LightSkyBlue;
}
.son {
position: absolute;
bottom: 0px;
right: 10px;
width: 200px;
height: 200px;
background-color: tomato;
}
</style>
</head>
<body>
<div class="grandfather">
grandfather
<div class="father">
father
<div class="son">
son
</div>
</div>
</div>
</body>
</html>
没有祖先元素,son以浏览器为准:
<!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;
bottom: 0px;
right: 10px;
width: 200px;
height: 200px;
background-color: tomato;
}
</style>
</head>
<body>
<div class="son"></div>
</body>
</html>
绝对定位会影响后面的盒子。
给son1加上绝对定位后,son2占据了son1原来的位置。