2017-05-10 82 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上的邊距會摺疊在父級之外。