当元素的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>相对定位、绝对定位、固定定位使用场景</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
height: 10000px;
}
.location_fixed {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100px;
background-color: #9356f4;
}
.location_relative {
position: relative;
top: 100px;
width: 200px;
height: 200px;
margin: 0;
background-color: pink;
}
.location_absolutely {
position: absolute;
width: 200px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="location_fixed">
<h1>固定定位</h1>
</div>
<div class="location_relative">相对定位</div>
<div class="location_absolutely">绝对定位</div>
</body>
</html>
主要使用场景:可以在浏览器页面滚动时元素的位置不会改变时候使用。