【问题标题】:How can I do an absolute div (with some content inside) stretched to its parent div?如何将绝对 div(内部包含一些内容)拉伸到其父 div?
【发布时间】:2018-05-25 02:19:12
【问题描述】:

假设我已经将一个 div 定位为绝对的,以便使用 left 和 top 移动它,但我希望它的内容拉伸到它的父容器 div,它具有特定的高度和宽度(即宽度为 300px 和高度200 像素)。

我怎样才能实现它?

【问题讨论】:

    标签: css


    【解决方案1】:

    你需要做两件事:

    1. 给父母一个 position 的任何东西,而不是 static(默认值)
    2. 给家长一个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>

    如果您想同时使用偏移量阻止子元素扩展到父容器之外,最好的办法是使用 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-25
      相关资源
      最近更新 更多