前端学习笔记54-固定定位
前面学了相对定位和绝对定位,接下来学习固定定位。
position:fixed
固定定位也是一种绝对定位,大部分特点与绝对定位一样。不同的是,固定定位的参照点是浏览器的视口。
视口是啥?
看代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1{
width: 100px;
height: 100px;
background-color: #bfa;
}
.box2{
width: 100px;
height: 100px;
background-color: orange;
position: fixed;
top: 0;
left:0;
}
.box3{
width: 100px;
height: 100px;
background-color: orchid;
}
.box4{
height: 200px;
width: 200px;
background-color: peru;
position: relative;
}
.box5{
height: 150px;
width: 150px;
background-color: red;
position: relative;
}
</style>
</head>
<body>
<div class="box1">1</div>
<div class="box4">
4
<div class="box5">
<div class="box2">2</div>
</div>
</div>
<div class="box3">3</div>
</body>
</html>
从上图可以看到,虽然给box4和box5都开启了相对定位,但是box2还是在左上角,所以它的参考点永远是浏览器视口的左上角。
这里可能解释不清楚视口,所以再给body设置高度。
body{
height: 2000px;
}
我滑动了滚动条,然后其他几个box都看不见了,只有box2看得见。这就很好理解视口了。