子项不呈现父项的%height?

时间:2018-07-24 05:40:53

标签: html css

Here是指向我的小提琴的链接,以供参考。

.container {
  background-color: gray;
  position: relative;
  padding: 20px;
  height: 70%;
  /* uncomment this and will work as expected */
  /* height: 70px; */
}

.child1 {
  width: 75%;
  display: inline-block;
  height: 100px;
}

.child2 {
  background-color: green;
  width: 75%;
  float: right;
  height: 100%;
}
<div class="container">
  <div class="child1">Child 1</div>
  <div class="child2">Child 2</div>
</div>

计算child1之后,父辈的高度为100px(可以在devtools中看到)。 Child2被应用了100%的高度,等于100px,但是在计算样式中(可以在devtools中看到)它显示为0px。

我认为这是因为父母的身高是在运行时计算的。有帮助吗?

2 个答案:

答案 0 :(得分:1)

因为父母的身高也是百分比。它将在以下情况下工作:

  • 您的div的父母身高为100%
  • 您的div的父级具有固定的高度
  • 您的div的父级具有一些内容,因此具有一定的高度。

目前,它不知道100%是什么。

答案 1 :(得分:0)

使用高度百分比值需要以下之一:

  1. 如果所有父元素的高度都为百分比,请 ALL 父元素明确定义其高度。
  2. 否则,父元素必须具有固定的高度(而不是%)。

您的.container元素的父级可能没有定义高度值,或者该元素的父级等等。

请记住html和body元素也要计数。

html, body
{
    height: 100%;
}