另一个宽高比div内的宽高比div不按预期工作

时间:2017-12-07 14:42:39

标签: html css html5 css3 pseudo-element

我的代码出了什么问题?为什么内部div(两个)填充外部div而不是将其纵横比保持padding-bottom



.one {
  position: relative;
  background: #990000;
  background-size: contain;
}

.one:before {
  content: "";
  width: 1px;
  margin-left: -1px;
  float: left;
  height: 0;
  padding-bottom: 40%;
}

.one:after {
  content: "";
  display: table;
  clear: both;
}

.two {
  position: relative;
  top: 0;
  background: #009900;
}

.two:before {
  content: "";
  width: 1px;
  margin-left: -1px;
  float: left;
  height: 0;
  padding-bottom: 20%;
}

.two:after {
  content: "";
  display: table;
  clear: both;
}

<div class="one">
  <div class="two"></div>
</div>
&#13;
&#13;
&#13;

https://jsfiddle.net/mhk99j8z/

1 个答案:

答案 0 :(得分:0)

这是因为你没有清除你的one:before浮动 - 你的one:after在两个之后 - :after追加到一个元素的末尾(在所有其他之后)元素)

&#13;
&#13;
.one {
  position: relative;
  background: #990000;
  background-size: contain;
}

.one:before {
  content: "";
  width: 1px;
  margin-left: -1px;
  float: left;
  height: 0;
  padding-bottom: 40%;
}
    
.two {
  clear:left;             /* remove one:after and clear on two */
  position: relative;
  top: 0;
  background: #009900;
}

.two:before {
  content: "";
  width: 1px;
  margin-left: -1px;
  float: left;
  height: 0;
  padding-bottom: 20%;
}

.two:after {
  content: "";
  display: table;
  clear: both;
}
&#13;
<div class="one">
  <div class="two"></div>
</div>
&#13;
&#13;
&#13;