假设我已经将div定位为绝对,以便使用left和top移动它,但我希望它的内容延伸到其父容器div,它具有特定的高度和宽度(即宽度为300px,高度为200px) . ¿我怎样才能实现它?谢谢
您需要做两件事:
给父母一个 position 除 static 以外的任何东西(默认)
static
给父母一个 width 和 height
然后简单地给绝对定位的孩子一个亲戚 width 和 height .
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>
如果你想利用偏移 and 来阻止子元素在父容器外扩展,你最好的办法是利用 calc() 从 width 中减去 left 偏移量,并从 height 中减去 top 偏移量:
left
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); }
1 回答
您需要做两件事:
给父母一个 position 除
static
以外的任何东西(默认)给父母一个 width 和 height
然后简单地给绝对定位的孩子一个亲戚
width
和height
.这可以在以下内容中看到:
如果你想利用偏移 and 来阻止子元素在父容器外扩展,你最好的办法是利用 calc() 从
width
中减去left
偏移量,并从height
中减去top
偏移量: