解决子元素定位后元素被裁剪,隐藏不见问题

示例如下:

<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>

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

在这里插入图片描述
但是实际展示是
在这里插入图片描述

蓝色方块不见,最后发现是 父级 b盒子中的overflow属性造成的影响,感觉就像清除了定位一样

和将c盒子用浮动实现,效果一样


//css
    .c{
      float: left;
      width: 100px;
      height: 100px;
      background: blue;
      margin-left: 300px;
    }

这里记住了一个坑,overflow不仅能清除float,也能清除定位 删除就能看见定位元素

但是我就是需要在b盒子使用overflow属性,如何解决呢?

在外层再套一个和b盒子一样大小的盒子用于定位,将定位定在外层的盒子中就可以

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

//css
  <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>

猜你喜欢

转载自blog.csdn.net/marendu/article/details/106791083