首页 > 解决方案 > 高度为 100% 的容器适合内容,未设置高度将高度设置为父级的 100%

问题描述

所以我有一个height属性是css的案例。

根据[定义](https://www.w3schools.com/cssref/pr_dim_height.asp)一个容器height: 50%

将元素的高度设置为父元素高度的 50%

这里有 2 个代码片段,唯一的区别是 height 属性设置为 100% 或根本没有设置

设置高度属性: JSFIDDLE

.parent {
  display: flex;
  min-height: 300px;
  background-color: grey;
  padding: 30px;
}

.child {
  position: relative;
  background-color: red;
  height: 100%;
}

.content {
  margin: 20px;
  height: 50px;
  width: 100px;
  background-color: blue;
}
<div class="parent">
  <div class="child">
    <div class="content"></div>
    <div class="content"></div>
    <div class="content"></div>
  </div>
</div>

没有设置高度属性(按预期工作):JSFIDDLE

.parent {
  display: flex;
  min-height: 300px;
  background-color: grey;
  padding: 30px;
}

.child {
  position: relative;
  background-color: red;
}

.content {
  margin: 20px;
  height: 50px;
  width: 100px;
  background-color: blue;
}
<div class="parent">
  <div class="child">
    <div class="content"></div>
    <div class="content"></div>
    <div class="content"></div>
  </div>
</div>

对我来说,这与 height 属性的定义相反,怎么会?我注意到,如果没有display: flex父母,行为是不同的,但是height: 100%什么也不做。

标签: htmlcssflexbox

解决方案


推荐阅读