常见的position定位方式如下:
1.static 默认值。
(即没有定位)遵循正常的文档流对象。
2.fixed
生成绝对定位的元素,通常相对于浏览器窗口或 iframe 进行定位。
元素的位置相对于浏览器窗口是固定位置。
即使窗口是滚动的它也不会移动:
这就如一些页面上的侧边导航条一样,不管你的页面如何滚动,导航条的位置始终未有任何改变。
3.relative
生成相对定位的元素,相对定位元素的定位是相对其原本位置。其原本的位置不会被其他元素所占用,而absolute则不同,其原本的位置会空出来,如果后边还有元素,那他就会占用该空间
注:相对定位元素经常被用来作为绝对定位元素的容器块。但是其他定位也可以作为绝对定位元素容器,static不行,因为他的意思是元素没有定位,这个为默认值。
例子1:相对定位,其原本的位置不被占用
<!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>
/* 去掉默认样式 */
*{
margin: 0;
padding: 0;
}
.stage{
position: relative;
}
.box{
width: 300px;
height: 150px;
font-size: 30px;
color: whitesmoke;
font-weight: bolder;
margin-bottom: 10px;
}
.box1{
background-color: red;
}
.box2{
position: relative;
left: 100px;
background-color:blueviolet;
}
.box3{
background-color: green;
}
</style>
</head>
<body>
<div class="stage">
<div class="box box1">1</div>
<div class="box box2">我是相对定位的</div>
<div class="box box3">3</div>
</div>
</body>
</html>
例子2:绝对定位,其原本的位置会被占用
<!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>
/* 去掉默认样式 */
*{
margin: 0;
padding: 0;
}
.stage{
position: relative;
}
.box{
width: 300px;
height: 150px;
font-size: 30px;
color: whitesmoke;
font-weight: bolder;
margin-bottom: 10px;
}
.box1{
background-color: red;
}
.box2{
position: absolute;
left: 100px;
background-color:blueviolet;
}
.box3{
background-color: green;
}
</style>
</head>
<body>
<div class="stage">
<div class="box box1">1</div>
<div class="box box2">我是绝对定位的</div>
<div class="box box3">3</div>
</div>
<script>
</script>
</body>
</html>
4.absolute
生成绝对定位的元素, 相对于最近一级的 不是 static(static是没有定义的) 的父元素来进行定位,如果没有找到的话,最终是根据body进行定位。
注:定位使元素的位置与文档流无关,因此不占据空间。