第9天: position 布局之 fixed、sticky

今天是关于 position 最后一节内容,前两节内容回顾:
第7天: position 布局之绝对布局 absolute
第5天:position 布局之相对布局 relative

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>

sticky

在端开发中,iOS 中有一种独特的效果「悬停」,当滚动到某个位置时,某个 view 会悬停到某个位置不动,比如微信通讯录的字母标签当滑动的时候字母标签会悬停。

在 web 中通过 position: sticky 来实现这种效果。我觉得下面这段英文更能让你理解 sticky 的作用:

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

我们通过 sticky 实现一个悬停效果,当滑动到某个位置时,用户信息会悬停在顶部:


滑动时悬停:

代码实现:

<!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,送出一句祝福的话吧!!!


推荐阅读:
第5天:position 布局之相对布局 relative
死磕 CSS 布局 - 前端小课第二阶段

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值