html - 百分比高度与最小高度的行为是什么?

标签 html css height

<分区>

当您将 min-height 给 parent 并将 percentage height 给 child 时, child 不会获得任何高度。

.p {
  min-height: 50vh;
  background-color:beige;
  
}

.c {
  height: 50%;
  background-color: red;
}
<div class="p">
  <div class="c"> hi </div>
</div>

但是如果你给parent明确的高度,即使它小于min-height,child得到一个高度,但是它是相对于min-height而不是提供的高度(当height < min-height时)

.p {
  min-height: 50vh;
  height: 1px;
  background-color:beige;
  
}

.c {
  height: 50%;
  background-color: red;
}
<div class="p">
  <div class="c"> hi </div>
</div>

  1. 首先,我想了解这种行为
  2. 我怎样才能给 child 高度的百分比,只有 parent 的最小高度

最佳答案

这是百分比高度的工作原理 https://developer.mozilla.org/en-US/docs/Web/CSS/height我正在使用此链接,因为它更容易找到,如其他答案中所述,规范链接 https://www.w3.org/TR/CSS22/syndata.html#value-def-percentage

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to auto. A percentage height on the root element is relative to the initial containing block.

您必须向下滚动才能找到这个(规范部分)

在您的情况下,由于您没有指定父级的高度,因此您的子级高度计算为自动,这就是您在示例中看到的

这里是如何在不指定父级高度的情况下使用绝对位置来获得百分比高度的工作

.p {
  min-height: 50vh;
  background-color:beige;
  position: relative;
}

.c {
  height: 50%;
  background-color: red;
  position: absolute;
}
<div class="p">
  <div class="c"> hi </div>
</div>

注意 - 你 parent 的高度 = min-height 和 height 之间的较大值,这就是你的第二种情况有效的原因

老实说,添加 1px 的高度作为一种解决方法,可以在不定义固定高度(因为最小高度覆盖)的情况下为 child 工作的百分比是一个很好的解决方法。

关于html - 百分比高度与最小高度的行为是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56114679/

相关文章:

html - 形式低于所有其他李的李元素

css - 我可以动态调整 css 设置的 div 边框的高度吗?

javascript - 填充 HTML 下拉列表 onclick

javascript - 相同的按钮样式但不同的输出

html - 如何使用 CSS 和 Bootstrap 在面板 div 顶部添加图像图标?

html - 如何使标题触摸页面顶部?

html - 边距自动、 float 和父高度

jquery - div 在鼠标悬停事件期间未保持

嵌套元素的 css z-index 问题

javascript - CSS 缩放和居中页面