【发布时间】:2018-05-25 02:19:12
【问题描述】:
假设我已经将一个 div 定位为绝对的,以便使用 left 和 top 移动它,但我希望它的内容拉伸到它的父容器 div,它具有特定的高度和宽度(即宽度为 300px 和高度200 像素)。
我怎样才能实现它?
【问题讨论】:
标签: css
假设我已经将一个 div 定位为绝对的,以便使用 left 和 top 移动它,但我希望它的内容拉伸到它的父容器 div,它具有特定的高度和宽度(即宽度为 300px 和高度200 像素)。
我怎样才能实现它?
【问题讨论】:
标签: css
你需要做两件事:
然后简单地给绝对定位的孩子一个相对的width 和height。
这可以在下面看到:
.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>
【讨论】: