不要乱用position:fixed

经常会有一个需求,在一个固定窗口内容滚动,底下有操作按钮需要固定,不随着滚动,一般第一个念头就是用固定定位position: fixed,但是fixed是以窗口为父元素去定位的,这么做肯定是错的,需要正确使用相对定位和绝对定位

<!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>Document</title>
<style>
.wrap {
    position: relative;
    width: 200px;
    border: 1px solid #ccc;
}
.content{
    width: 200px;
    height: 300px;
    overflow: auto;
    margin-bottom: 50px;
    border: 1px solid #ccc;
}
.item {
    width: 100%;
    height: 100px;
    background: red;
    margin-bottom: 10px;
}
.btn {
    position: absolute;
    bottom: 0;
    background: #fff;
    width: 100%;
    height: 50px;
}
</style>
</head>
<body>
<div class="wrap">
    <div class="content">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="btn">按钮</div>
    </div>
</div>
</body>
</html>

position:fixed 相对父元素定位

position:fixed是对于浏览器窗口定位的,要实现相当于父元素定位,可以这样:

不设置fixed元素的top,bottom,left,right,只设置margin来实现。

这种方法本质上fixed元素还是相当于窗口定位的,实现效果上是相对于父元素定位。

此外,position:fixed元素会受到父元素的影响,而出现不能以窗口进行定位:

  1. 因为fixed元素并不总是相对于视窗进行定位的,父元素发生变换,也就是transfrom属性发生改变,如平移或旋转,会对固定定位的子元素产生影响 例子:固定定位不固定。
<div class='container'>
  <div class='fix'>我固定了吗?</div>
</div>
.container{
  width: 200px;
  height: 200px;
  line-height: 200px;
  text-align: center;
  background: #6699FF;
  animation: move 4s cubic-bezier(0.4,0,0.6,1) infinite;
}
.fix{
  position: fixed;
  top: 20px;
  left: 20px;
  width: 200px;
  height: 200px;
  background: #9966FF;
  color:#FFF;
}
@keyframes move{
  0% {transform:translateX(100px);}
  50% {transform:translateX(500px);}
  100% {transform:translateX(100px);}
}
  1. 如果父级元素的z-index的层次比同级元素低,就算fixedz-index比父级高,也会被父级同级元素遮挡。

因此,position:fixed元素若要以窗口进行定位,最好是放在body根标签下

  • 14
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值