前言
今天说一下大家都经常用的定位:fixed;那有人会说这有啥好说的,不就是不随滚动条滚动,定位根据浏览器视口决定嘛;在学css的时候就已经知道了;
但真是这样吗?今天就带大家看一下不一样的fixed定位
常规
常规用法确实是跟大家想的一样定位根据浏览器视口决定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: pink;
position: relative;
margin: 50px 0 0 50px;
}
.chidren {
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
left: 50px;
position: fixed;
}
</style>
</head>
<body>
<div class="box">
<div class="chidren"></div>
</div>
</body>
</html>

定位很符合我们所了解的,但是当我给父元素加上一些css属性之后,就发现不一样了
不一样的fixed定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: pink;
position: relative;
margin: 50px 0 0 50px;
transform: translateX(0);
}
.chidren {
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
left: 50px;
position: fixed;
}
</style>
</head>
<body>
<div class="box">
<div class="chidren"></div>
</div>
</body>
</html>
结果:

发现没有,定位怎么相对于父元素了,不就加了一个transform: translateX(0);,难道是transform的问题吗?
没错就是transform的问题
*If the element has position: fixed, the transform creates a containing block for the element and its fixed-position descendants, just like position: relative does for absolute-positioned descendants.*这是w3c的描述,大致意思是:如果元素是一个fixed,那么transform会创建一个包含块,这个包含块会影响后代的fixed布局,就像relative和absolute的定位关系(英语不好,随意翻译的),所以说fixed布局不能说是按照浏览器视口来定位的
还有哪些属性会影响fixed呢
- perspective: 非 none 值 ;
- filter: 非 none 值(如 filter: blur(2px))
- will-change: transform/perspective/filter
大家可以自行试验一下,这里就不多实现了
总结
以上就是关于fixed定位的一些可能在开发中令人不解的东西,如果又错误欢迎指出
403

被折叠的 条评论
为什么被折叠?



