gpt4 book ai didi

css - 我怎样才能做一个绝对的 div(里面有一些内容)延伸到它的父 div?

转载 作者:太空宇宙 更新时间:2023-11-04 07:18:49 24 4
gpt4 key购买 nike

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

我怎样才能实现它?

最佳答案

你需要做两件事:

  1. 给 parent 一个 position 除了 static(默认值)
  2. 给 parent 一个 width height

然后简单地给绝对定位的 child 一个相对的宽度高度

这可以从以下方面看出:

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

关于css - 我怎样才能做一个绝对的 div(里面有一些内容)延伸到它的父 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50520582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com