position: fixed 一定是相对于浏览器窗口进行定位吗?

5,264 阅读1分钟

前言

定位想必大家都非常熟悉,在构建页面的时候经常用到。那么看到标题肯定知道我要说的是不一定是相对于浏览器定位的。当然这只是一个小知识点,先前我不知道这个小知识点,如果你知道的话,那就略过本文就好啦。

实践一下

简单的在页面上写一个居中的盒子看看效果。

<head>
  <style>
    body {
      background: gray;
    }
    .box {
      width: 200px;
      height: 200px;
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: blue;
    }
  </style>
</head>
<body>
  <div class="box"></div>
</body>

image.png

目前一切正常

那么再在这个盒子里套一个盒子。并且加上 fixed 定位呢?

<head>
  <style>
    body {
      background: gray;
    }
    .box {
      width: 200px;
      height: 200px;
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: blue;
    }
    .box-inside {
      width: 100px;
      height: 100px;
      position: fixed;
      top: 0;
      left: 0;
      background: red;
    }
  </style>
</head>
<body>
  <div class="box">
    <div class="box-inside"></div>
  </div>
</body>

image.png

哦ho!? 这是咋回事呢?里面的盒子设置的 top: 0; left: 0 但是却是基于外层的盒子定位的。难道 fixed 布局不能嵌套布局吗?

重新认识一下

有问题肯定要翻阅文档 MDN Web Docs,重新学习一下。

image.png
可以看到。fixed 中有这么一段话:

当元素祖先的 transformperspective 或 filter 属性非 none 时,容器由视口改为该祖先

那么再改一下刚刚的 demo 看看

.box {
  width: 200px;
  height: 200px;
  position: fixed;
  top: calc(50% - 100px);
  left: calc(50% - 100px);
  background: blue;
}

image.png

这样子就达到了原本想要的效果啦!

结尾

今天又get到了一个小知识点(让我中个月饼吧 T^T)