经常会有一个需求,在一个固定窗口内容滚动,底下有操作按钮需要固定,不随着滚动,一般第一个念头就是用固定定位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
元素会受到父元素的影响,而出现不能以窗口进行定位:
- 因为
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);}
}
- 如果父级元素的
z-index
的层次比同级元素低,就算fixed
的z-index
比父级高,也会被父级同级元素遮挡。
因此,position:fixed
元素若要以窗口进行定位,最好是放在body
根标签下