【发布时间】:2018-05-24 17:01:49
【问题描述】:
我想通过纯 CSS 创建一个方形 div,height 是动态的,width 将基于 height 进行缩放。
正如我们在下面的片段中看到的,container 高度是基于其内容的动态。
红色square 占据container 的全高,宽度应等于height。
我知道我们可以maintain aspect ratio of a div base on its width 但当height 是动态时我找不到方法。
任何帮助,将不胜感激!非常感谢!
请注意:高度是动态的,因此the solution with vh 不起作用,并且片段只是一个游乐场。
#container {
width: 400px;
padding: 20px;
border: solid 1px black;
position: relative;
}
.square {
position: absolute;
top: 0;
right: 0;
bottom: 0;
background-color: red;
width: 100px /*Hmm its just a dummy value*/
}
<div id="container">
<div class="content">
I'm a dynamic content
</div>
<div class="square"></div>
</div>
【问题讨论】:
-
可以使用css的calc函数。 w3schools.com/cssref/func_calc.asp
-
@LucasRosenberger:我知道
calc(),但我如何使用它来计算基于高度的宽度? -
抱歉误解了您的问题。我认为你需要为这个用例使用 js。
-
@LucasRosenberger:是的,谢谢!由于性能原因,我只是在寻找一个纯 css 解决方案。