首页 文章

我怎样才能将一个绝对div(内部有一些内容)拉伸到其父div?

提问于
浏览
0

假设我已经将div定位为绝对,以便使用left和top移动它,但我希望它的内容延伸到其父容器div,它具有特定的高度和宽度(即宽度为300px,高度为200px) . ¿我怎样才能实现它?谢谢

1 回答

  • 1

    您需要做两件事:

    • 给父母一个 positionstatic 以外的任何东西(默认)

    • 给父母一个 widthheight

    然后简单地给绝对定位的孩子一个亲戚 widthheight .

    这可以在以下内容中看到:

    .parent {
      position: relative;
      background: red;
      width: 200px;
      height: 200px;
    }
    
    .absolute {
      position: absolute;
      background: blue;
      top: 50px;
      left: 50px;
      width: 100%;
      height: 100%;
    }
    
    <div class="parent">
      <div class="absolute"></div>
    </div>
    

    如果你想利用偏移 and 来阻止子元素在父容器外扩展,你最好的办法是利用 calc()width 中减去 left 偏移量,并从 height 中减去 top 偏移量:

    .parent {
      position: relative;
      background: red;
      width: 200px;
      height: 200px;
    }
    
    .absolute {
      position: absolute;
      background: blue;
      top: 50px;
      left: 50px;
      width: calc(100% - 50px);
      height: calc(100% - 50px);
    }
    
    <div class="parent">
      <div class="absolute"></div>
    </div>
    

相关问题