美文网首页
position:fixed窗口定位的不生效

position:fixed窗口定位的不生效

作者: 羊驼626 | 来源:发表于2022-03-16 16:52 被阅读0次

    问题1:position:fixed样式不生效

    原因:position:fixed的元素的最近一个父级元素有transform样式时(无论该父级元素是否有position属性),则该元素会以他的父级元素为参照物实现定位
    解决办法:去掉父级元素的transform

    <div :class="$style['content']">
      padding-top: 54px;
      width: 100%;
      height: 200px;
      background: yellow;
      transform: translateY(54px);
      <div :class="$style['modal']">
        position: fixed;
        top: 0;
        left: 50%;
        background: red;
        z-index: 999;
        color: #fff;
      </div>
    </div>
    
    .content {
         padding-top: 54px;
         width: 100%;
         height: 200px;
         background: yellow;
         transform: translateY(54px);
         .modal {
           position: fixed;
           top: 0;
           left: 50%;
           background: red;
           z-index: 999;
           color: #fff;
         }
       }
    

    问题2:position:fixedz-index不生效

    从父原则:
    通过用fixed absolute relative定位的元素。
    其子元素和父辈元素比较z-index的时候,采用父元素的z-index值去比较。同辈之间采用自己的z-index比较。

    原因:当dom标签添加position:fixed样式后,改标签的z-index会以最近一个有定位属性position的父级元素的z-index值为基准进行比较
    解决办法:去掉父级元素的z-index
    示例: modal窗口定位,但modal的父级content有定位属性,且有z-index: 1,由于content的z-index比header的z-index小,导致modal即使z-index为999,也无法超过header的层级;当把content的z-index去掉之后,modal的层级则会超过header,盖在header上方

    <div :class="$style['container']">
      <div :class="$style['header']">
        position: absolute;
        top: 0;
        width: 100%;
        height: 54px;
        background: blue;
        z-index: 2;
        color: #fff;
      </div>
      <div :class="$style['content']">
        position: absolute;
        top: 0;
        padding-top: 54px;
        width: 100%;
        height: 200px;
        background: yellow;
        z-index: 1;
        <div :class="$style['modal']">
          position: fixed;
          top: 0;
          left: 50%;
          background: red;
          z-index: 999;
          color: #fff;
        </div>
      </div>
    </div>
    
    .header {
         position: absolute;
         top: 0;
         width: 100%;
         height: 54px;
         background: blue;
         z-index: 2;
         color: #fff;
       }
       .content {
         position: absolute;
         top: 0;
         padding-top: 54px;
         width: 100%;
         height: 200px;
         background: yellow;
         z-index: 1;
         .modal {
           position: fixed;
           top: 0;
           left: 50%;
           background: red;
           z-index: 999;
           color: #fff;
         }
       }
    

    相关文章

      网友评论

          本文标题:position:fixed窗口定位的不生效

          本文链接:https://www.haomeiwen.com/subject/qympdrtx.html