当孩子有边距

时间:2017-05-10 02:49:21

标签: html css css3

我正在使用来自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删除“border”CSS,那么它的高度为0.这可以在这里的片段和在这里摆弄:https://jsfiddle.net/s2b4xr1a/2/

由于我的真实应用程序不具有该边框,我如何才能显示div并根据其子项获得正确的高度?另外,为什么会这样呢?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

除非框之间有边框或填充,否则垂直边距不会折叠。因此,如果您想在布局中保留效果,但需要删除边框,请添加1px的填充。

如果您有需要保留的高度/宽度设置,请添加box-sizing: border-box,这会将padding(以及border,btw)计入高度/宽度计算。< / p>

&#13;
&#13;
#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;
}
&#13;
<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>
&#13;
&#13;
&#13;

revised fiddle