在这里,我试图使 div 的宽度与其高度完全相同,以使其保持完美的正方形。高度是其父 div 的百分比,因此没有其高度的精确像素值。
如果我不知道确切的像素高度,如何使 div 完全正方形?
我在下面给出了一个链接来演示我所说的内容。在示例中,我希望青色 div 动态转换其宽度以匹配其高度尺寸,从而使其保持完美的正方形。我希望能够在 CSS 代码中做到这一点,但如果不能,也没关系。
https://jsfiddle.net/5pdLpqrg/
CSS:
#parent{
height: 70px;
width: 450px;
background: #999;
resize: both;
overflow: auto;
}
#perfect_square{
height: 78%;
width: 80px;
background: cyan;
}
最佳答案
这是一个仅 CSS 解决方案:
#parent {
width:350px;
height:200px;
background:silver;
}
#container {
display: inline-block;
position: relative;
width: 50%;
}
#container:after {
content: '';
display: block;
margin-top: 100%;
}
#perfect_square {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: cyan;
}
<div id="parent">
<div id="container">
<div id="dummy"></div>
<div id="perfect_square">
</div>
</div>
</div>
另一个仅 CSS 解决方案:
.parent {
width:600px;
height:500px;
background:silver;
}
.perfect_square {
width: 20%;
height: 0;
padding-bottom: 20%;
background:cyan;
}
<div class="parent">
<div class="perfect_square"></div>
</div>
希望有帮助!
关于html - 动态强制 div 的宽度等于其高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34669951/