由于我是网络编程的新手,我还没有在 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];
}
Run Code Online (Sandbox Code Playgroud)
HTML 代码如下所示:
<div class="parent">
<div class="child"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
目前孩子的宽度保持不变,因为父母的宽度保持不变。当父高度调整大小时,我希望孩子的宽度变小。
提前致谢。
只需将父元素的 height 属性值分配给css 变量,然后使用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;
}Run Code Online (Sandbox Code Playgroud)
<div class="parent">
<div class="child"></div>
</div>Run Code Online (Sandbox Code Playgroud)
注意,如果您需要向后兼容 IE11,您可以使用 polyfill,如其他SO 线程上的最佳答案所示。