代码之家  ›  专栏  ›  技术社区  ›  Ivan Jeffrey Zhao

在网格中定位的div内的绝对定位

css
  •  2
  • Ivan Jeffrey Zhao  · 技术社区  · 8 年前

    我正在尝试CSS网格布局,目前面临一个问题。我想使用 position: absolute 对于位于网格中的div的子级。正如您在下面看到的(代码段),红色框设置为 是一个孩子 .left

    如何使红色框在视觉上保持在橙色分区(左侧),而不会在棕色分区(右侧)中“溢出”?

    我试过设置 position: relative

    下面是显示问题的简化版本(您可以修改该值以查看分隔符的移动)

    html,
    body,
    section {
      height: 100%;
      margin: 0px;
      padding: 0px;
    }
    
    .window {
      display: grid;
      grid-template-areas: "first seperator last";
      grid-template-columns: 100px 10px auto;
      /*                     | this one       */
    }
    
    .left {
      background: #ff9e2c;
      grid-area: first;
      position: relative;
    }
    
    .right {
      background: #b6701e;
      grid-area: last;
    }
    
    .separator {
      background: white;
    }
    
    .abs-pos {
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
      top: 100px;
      left: 75px;
    }
    <section class="window">
      <div class="left">
        <div class="abs-pos"></div>
      </div>
      <div class="separator"></div>
      <div class="right"></div>
    </section>

    以下是问题的GIF: enter image description here PS: .separator div .左边 .right . 它基本上改变了财产 grid-template-columns: 100px 10px auto 属于 .window

    2 回复  |  直到 8 年前
        1
  •  1
  •   Don Bob    8 年前

    背景 overflow: hidden; .left 窗格将阻止红色框显示在其父边界之外。

    html,
    body,
    section {
      height: 100%;
      margin: 0px;
      padding: 0px;
    }
    
    .window {
      display: grid;
      grid-template-areas: "first seperator last";
      grid-template-columns: 100px 10px auto;
      /*                     | this one       */
    }
    
    .left {
      background: #ff9e2c;
      grid-area: first;
      position: relative;
      overflow: hidden;
    }
    
    .right {
      background: #b6701e;
      grid-area: last;
    }
    
    .separator {
      background: white;
    }
    
    .abs-pos {
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
      top: 100px;
      left: 75px;
    }
    <section class="window">
      <div class="left">
        <div class="abs-pos"></div>
      </div>
      <div class="separator"></div>
      <div class="right"></div>
    </section>
        2
  •  1
  •   Harry    8 年前

    你试过给你的班级一个z指数吗

      z-index: -1;
    

    Z索引设置堆栈顺序并与定位元素一起工作。一、 e绝对、相对、固定。

    所以如果你能给你的。右和或。分离器a级位置相对它应该工作。

     .right {
         position:relative;
         z-index: 1;
    }
    
     .separator {
         position:relative;
         z-index: 1;
     }
    
     .abs-pos {
         position:absolute;
         z-index: -1;
     }