gpt4 book ai didi

html - 在纯CSS中设置相对于其 parent 高度的 child 宽度

转载 作者:搜寻专家 更新时间:2023-10-31 22:53:10 24 4
gpt4 key购买 nike

由于我是网络编程的新手,所以我在 CSS 方面还没有获得太多经验。目前我正在构建一个带有可调整大小标题的 Web 应用程序。因此我想知道是否可以相对于其父 div 的高度设置子 div 的宽度。

我知道如何处理 javascript 代码中的问题,但我更喜欢纯 css 解决方案。

CSS 代码看起来像这样:

.parent {
position: relative;
height: 200px;
width: 600px;
}
.parent .resized {
height: 100px;
}

.child {
position: absolute;
height: 20%;
width: 10% [of parent height];
}

HTML 代码如下所示:

<div class="parent">
<div class="child"></div>
</div>

目前 child 的宽度保持不变,因为 parent 的宽度保持不变。当父级高度调整大小时,我希望子级宽度变小。

提前致谢。

最佳答案

只需将您 parent 的高度属性值分配给一个 css variable 然后使用 calc() 将子元素的宽度指定为父元素高度的 10%。

检查并运行下面的代码片段以获得我上面描述的实际示例:

.parent {
position: relative;
--parentHeight: 300px;
height: var(--parentHeight);
width: 600px;
background-color: red;
}
.parent .resized {
height: 100px;
}

.child {
position: absolute;
height: 20%;
width: calc(var(--parentHeight) / 10);
background-color: green;
}
<div class="parent">
<div class="child"></div>
</div>

注意 如果您需要 IE11 的向后兼容性,您可以使用 polyfill,如其他 SO thread 的最佳答案中所示。 .

关于html - 在纯CSS中设置相对于其 parent 高度的 child 宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54288017/

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