1. 程式人生 > >transform 遇上 position: fixed

transform 遇上 position: fixed

最近遇到一個有意思的現象,以下 demo 中 fixed 的元素沒有相對 viewport 定位,而是相對於它的父元素進行定位。

<html>
  <head>
  <style>
    .parent {
      width: 200px;
      height: 300px;
      background: yellow;
      transform: scale(1);
     }
    .fixed {
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      background: red;
    }
   </style>
  </head>
  <body>
    <div class='parent'>
    parent
      <div class='fixed'>fixed</div>
    </div>
  </body>
</html>

  

 

在 w3c 中對 position: fixed 的[定義](https://www.w3.org/TR/css-position/#fixed-pos)如下:

Fixed positioning is similar to absolute positioning. The only difference is that for a fixed positioned box, the containing block is established by the viewport. 

大概意思就是,fixed 元素的塊級格式上下文 Block Formatting Context(BFC) 由 viewport 建立,也就是fixed 元素的 BFC 包含在根元素的 BFC 裡。

那以上 demo 的表現就說不過去了。為什麼呢