将 div 的高度设置为容器 div 的最大高度

3

我有一个容器 <div>,它具有 max-height 属性。这个 <div> 包含另一个 <div>,我希望子 <div> 能够增长到其容器的最大高度。

<div id='parent'>
  <div id='child'>
  </div>
</div>

当父级<div>高度固定时,这很容易实现,但我找不到解决方案,使子级<div>假定容器的最大高度。没有填充、边距或任何需要担心的东西 - 我只是需要子级<div>假定父级max-height。如何实现?

只是为了澄清你的解释,你的意思是说如果父元素的高度是154像素,那么子元素的高度也应该是154像素吗? - undefined
1
不完全是这样 - 我的意思是说,如果父元素的最大高度为154像素,则子元素的高度也应为154像素。 - undefined
我已经发布了答案,欢迎提出任何建议。 - undefined
只需将子元素的高度设置为100%即可使其使用父元素的高度。 - undefined
3个回答

2
将父元素的显示属性设置为flex,并将flex方向设置为列:

示例代码:

#parent {
  display: flex;
  flex-direction: column;
  max-height: 100px;
  border-bottom: 2px solid red; /** example - to show the effect on the parent **/
}

#child {
  height: 100vh;
  background: blue;
}
<div id="parent">
  <div id="child">
  </div>
</div>


似乎之所以能正常工作,是因为子div的高度大于最大高度,但是flex容器在没有溢出的情况下会裁剪高度。这种行为很奇怪,但还是谢谢。 - undefined
1
@Owen 不是奇怪的,而是合乎逻辑的:https://dev59.com/bFUL5IYBdhLWcg3w-sV4#49492522 - undefined

0

有几个要注意的地方,
1. 高度应该使用vh来实现响应式,特别是在处理高度CSS时更好。
2. 最好使用vh作为高度的单位。

.parent {
  max-height: 25vh;
  width: 15vw;
  background-color: aquamarine;
}

.child {
  background-color: brown;
  height: 25vh;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>

<div id='parent' class='parent'>
  <div id='child' class='child'>
  </div>
</div>

</body>

</html>


谢谢 - 但是我事先不知道父容器的最大高度,所以将子元素的高度值与容器的最大高度同步并不像简单。 - undefined

0
这很容易解决,只需给父级div添加一个高度即可。
<div class="parent">
  <div class="child"></div>
</div>

.parent{
  max-height:100px;
  width:500px;
  height:300px;
  background:coral;
}
.child{
  width:100%;
  height:100%;
  background:blue;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接