2017-05-10 84 views
1

我使用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显示并具有正确的高度基于其子?另外,为什么会发生这种情况?

回答

1

这与CSS collapsing margins有关,这会导致两个或多个框之间的垂直边距合并并形成单个边距。

除了在框之间存在边框或边框时,垂直边距不会折叠。所以,如果你想在布局中保留效果,但需要删除边框,请添加1px的填充。

添加,如果你有需要保留的高度/宽度设置,添加box-sizing: border-box,这将因素padding(和border,顺便说一句)中的高度/宽度计算。

#container { 
 
    display: block; 
 
    width: 100%; 
 
    position: relative; 
 
    border: 2px dashed blue; 
 
} 
 

 
#icon-container-border { 
 
    width: 25%; 
 
    position: relative; 
 
    display: block; 
 
    
 
    /* Removing the border property causes #icon-container to have 0 height */ 
 
    /* border: 2px dashed red; */ 
 
    
 
    padding: 1px; /* NEW */ 
 
} 
 

 
* { 
 
    box-sizing: border-box; /* NEW */ 
 
} 
 

 
#icon-container-no-border { 
 
    width: 35%; 
 
    /* Different width than first just to show that 1:1 ratio of width and height is preserved */ 
 
    position: relative; 
 
    display: block; 
 
    /* If border is added here, second div will show up as well, but why ?? */ 
 
    /* border: 2px dashed red; */ 
 
} 
 

 
.icon-spacer { 
 
    /* margin-top calculated based on width of parent */ 
 
    margin-top: 100%; 
 
} 
 

 
.icon { 
 
    background-color: black; 
 
    position: absolute; 
 
    top: 0; 
 
    bottom: 0; 
 
    left: 0; 
 
    right: 0; 
 
}
<div id="container"> 
 
    <div id="icon-container-border"> 
 
    <div class="icon-spacer"></div> 
 
    <div class="icon"></div> 
 
    </div> 
 
    <div id="icon-container-no-border"> 
 
    <div class="icon-spacer"></div> 
 
    <div class="icon"></div> 
 
    </div> 
 
</div>

revised fiddle

1

这是一个margin collapse的问题。边框将.icon-spacer的边距保留在#icon-container-border之内,从而给出该元素的高度。如果没有边框,.icon-spacer上的边距会折叠在父级之外。