解决overflow:hidden与定位一起使用子元素定位后元素被裁剪,隐藏不见问题

268 阅读1分钟

示例如下:

<body>
    <div class="b">
      b
      <div class="c">
        c
      </div>
    </div>
</body>

//css
  <style>
  
    .b{
      position: absolute;
      width: 300px;
      height: 300px;
      background: red;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      overflow: hidden;
      margin: auto;
    }
    .c{
      position: absolute;
      width: 100px;
      height: 100px;
      background: blue;
      left: 300px;
    }
  </style>

我定义了一个外层红色盒子绝对定位居中,又定义一个子元素蓝色盒子绝对定位,我需要的情况

image.png

但是实际展示是

image.png

审查元素发现,定位的蓝色盒子被裁减了

image.png

如果我们将容器b盒子的定位属性删除,c盒子又能正常显示,但却是相对于body定位

原因 这是因为在css中对overflow:hidden定义,如果定义overflow为包含容器,其子元素有定位属性,overflow将无法裁减,但当对包含容器也添加定位属性时,包含容器就能正常进行裁减

解决 但是我就是需要在b盒子使用overflow属性,如何解决呢? 按照上面出现的逻辑,我们的思路,就是给overflow属性的容器添加一个同样大小的父级用于定位

<body>
    <div class="a">
        <div class="b">
          b
          <div class="c">
            c
          </div>
        </div>
        
    </div>
</body>

  <style>
  .a{
      position: absolute;
      width: 300px;
      height: 300px;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      margin: auto;

  }
    .b{
      width: 300px;
      height: 300px;
      background: red;
      overflow: hidden;
    }
    .c{
      position: absolute;
      left: 300px;
      top: 0;
      width: 100px;
      height: 100px;
      background: blue;
    }
  </style>