【CSS】Position定位

1 Position的值

说明
absolute位置相对于最近的已定位父元素
fixed位置相对于浏览器窗口
relative位置相对其正常位置
static(默认)遵循正常文档流,不受 top、right、bottom、left 影响
sticky滚动阈值内为 relative ,滚动阈值外为 fixed

2 示例代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <style type="text/css">

        /* 设置项目大小和字体颜色 */
        .position div, .p-sticky {
            height: 100px;
            width: 100px;
            color: white;
        }

        .p-static {
            position: static;
            background-color: red;
        }

        .p-fixed {
            position: fixed;
            background-color: orange;
            right: 10px;
            top: 10px;
        }

        .p-relative {
            position: relative;
            background-color: gray;
            left: 20px;
            top: 20px;
        }

        .p-absolute {
            position: absolute;
            background-color: purple;
            left: 500px;
            top: 10px;
        }

        .p-sticky {
            position: sticky;
            background-color: brown;
            left: 300px;
            top: 10px
        }

        /* 填充一个项目,使页面能够滚动 */
        .add {
            width: 10px;
            height: 10000px;
        }
    </style>
    <title>position</title>
</head>
<body>

<div class="position">
    <div class="p-static">static</div>
    <div class="p-fixed">fixed<br>right10<br>top10</div>
    <div class="p-relative">relative<br>left20<br>top20</div>
    <div class="p-absolute">absolute<br>left500<br>top10</div>
</div>

<div class="p-sticky">sticky<br>left300<br>top10</div>

<div class="add"></div>

</body>
</html>

3 效果

页面:

  • static:相对于正常文档流
  • relative:相对于其正常位置,左20,上20
  • sticky:滚动前相对于正常位置,左300,上10
  • absolute:相对于父容器的位置,左500,上10
  • fixed:相对于浏览器窗口,右10,上10
    页面
    滚动一段:
  • fixed:相对于浏览器窗口,滚动后位置不变
  • sticky:仍在滚动阈值内,其位置还是 relative
    滚动一段
    滚动到底:
  • sticky:超过滚动阈值,其位置变为 fixed
    滚动到底
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搬金砖的小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值