CSS3--改變固定定位(fixed)的父級定位元素


css--改變固定定位(fixed)的父級定位元素

固定定位並不是只能相對 body 定位, 它的父級定位元素是可以自己設置的

MDN 原文

fixed
The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to the initial containing block established by the viewport, except when one of its ancestors has a transform, perspective, or filter property set to something other than none (see the CSS Transforms Spec), in which case that ancestor behaves as the containing block. (Note that there are browser inconsistencies with perspective and filter contributing to containing block formation.) Its final position is determined by the values of top, right, bottom, and left.

就是說如果父級設置了transform,perspective,filter且不為none,那么它的子孫元素就會相對於這個父級進行固定定位

效果示例

代碼

<!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>
      .father {
        width: 400px;
        height: 400px;

        /* 設置transform */
        /* transform: translateX(10px); */

        /* 設置perspective */
        perspective: 100px;

        /* 設置 filter */
        /* filter: grayscale(100); */

        background: cyan;
      }

      .child {
        width: 200px;
        height: 200px;
        background: darkgoldenrod;
      }

      .grand-child {
        /* 孫子元素開啟 固定定位 */
        position: fixed;
        /* 定位於底部 */
        bottom: 0;
        width: 100px;
        height: 100px;
        background: darkgreen;
      }
    </style>
  </head>
  <body>
    <div class="father">
      <div class="child">
        <div class="grand-child"></div>
      </div>
    </div>
  </body>
</html>

效果

效果圖
可以看到孫子元素設置了 fixed 定位, 但是時相對於 father 元素定位而不是 body


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM