fixed 的作用是把某个元素固定在「可视区域」的某个位置,即使发生滚动,它仍然会固定在某个位置,比如常见的导航栏会一直固定在页面顶部。它与使用 position:absolute 的元素表现形式都相同,除了它的布局区域只能是可视区域。下面的代码,红色区域会一直固定在顶部,无论如何滑动。
<style>
* {
margin: 0;
padding: 0;
}
body {
height: 1000px;
}
.box {
margin: 10px;
height: 400px;
background-color: #eeeeee;
}
p {
color: white;
font-size: 18px;
line-height: 40px;
}
p:nth-child(1) {
background-color: red;
position: fixed;
top: 0;
left: 0;
right: 0;
}
p:nth-child(2) {
background-color: green;
}
p:nth-child(3) {
background-color: black;
}
</style>
<body>
<div class="box">
<p>前端小课,每日一课</p>
<p>前端从0-1</p>
<p>我们今天学习 position:absolute 布局</p>
</div>
</body>
在端开发中,iOS 中有一种独特的效果「悬停」,当滚动到某个位置时,某个 view 会悬停到某个位置不动,比如微信通讯录的字母标签当滑动的时候字母标签会悬停。
This is basically a hybrid between relative and fixed position, which allows a positioned element to act like it is relatively positioned until it is scrolled to a certain threshold point (e.g. 10px from the top of the viewport), after which it becomes fixed.This can be used to for example cause a navigation bar to scroll with the page until a certain point, and then stick to the top of the page.---- MDN
代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Sticky</title>
<style>
* {
margin: 0;
padding: 0;
}
.header {
width: 100%;
height: 200px;
background-color: yellow;
}
.user {
width: 100%;
height: 64px;
background-color: cornflowerblue;
position: sticky;
top: 0px;
}
.con {
width: 100%;
height: 1800px;
background-color: bisque;
}
</style>
</head>
<body>
<div class="header">头部</div>
<div class="user">用户信息</div>
<div class="con">内容</div>
</body>
</html>
总结
本节课程介绍了 position 属性的最后两个值 fixed、sticky。fixed 在实际工作中使用场景比较多。
今天的打卡指令:
今天是 1024,送出一句祝福的话吧!!!
死磕 CSS 布局 - 前端小课第二阶段