我使用https://stackoverflow.com/a/6615994的技巧来得到一个div高度将等于百分比宽度。该结构是这样的:没有显式大小的块元素没有显示,当孩子有余量
#container {
display: block;
width: 200px;
height: 200px;
position: relative;
border: 2px dashed blue; /* just for demo */
}
#icon-container {
width: 25%;
position: relative;
display: block;
/* Removing the border property causes #icon-container to have 0 height */
border: 2px dashed red;
}
.icon-spacer {
/* margin-top calculated based on width of parent */
margin-top: 100%;
}
.icon {
/* My content will be displayed as a background-image in this element */
background-color: black;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
<div id="container">
<div id="icon-container">
<div class="icon-spacer"></div>
<div class="icon"></div>
</div>
</div>
虽然我是测试这一点,我遇到了以下行为:如果我从#icon-container
删除“边界” CSS,那么它得到的高度为0 。这可以在这里和这里的小提琴中看到:https://jsfiddle.net/s2b4xr1a/2/
由于我真正的应用程序不会有这个边界,我怎么能得到的div显示并具有正确的高度基于其子?另外,为什么会发生这种情况?