html - 如何在不使用 flexbox 的情况下让 <div> 填充剩余高度?

标签 html css

我有一个这样的 html 布局:

,-------------.
|,-----------.|
|| child 1   ||
|`-----------'|
|,-----------.|
|| child 2   ||
||           ||
||           ||
||           ||
||           ||
|`-----------'|
`-------------'

容器被赋予一个高度值,比如说 100vhchild 1 有一个固定的高度。我希望 child 2 自动填充剩余高度。

我知道有一个 flexbox 解决方案:

.container { 
    display: flex;
    flex-direction: column;
}
.child-1 {
    flex-shrink: 0;
    flex-grow: 0;
}
.child-2 {
    flex-grow: 1;
}

该解决方案单独使用,但如果我想要 child 2 中的第三个 child 3 具有 height: 100%,它失败。我需要使 child 2 flex 并将 child 3 设置为 flex-grow: 1

随着嵌套的加深,这种 flex 继承变得非常令人沮丧。它还违反了“关注点分离”,因为 DOM 结构仅在所有节点都正确设置为 display: flex 时才起作用。

下面是演示问题的 jsfiddle。

html,
body {
  margin: 0;
}

div {
  width: 100%;
}

.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.child-1 {
  height: 50px;
  flex-shrink: 0;
  flex-grow: 0;
}

.child-2 {
  flex-grow: 1;
}

.child-3 {
  height: 80%;
}


/* irrelevant styles like background-color etc. */

.container.irrelevant {
  width: 100px;
  background: green;
  float: left;
  margin-right: 20px;
}

.child-1.irrelevant {
  background: red;
}

.child-2.irrelevant {
  background: magenta;
}

.child-3.irrelevant {
  background: yellow;
}
<div class="container irrelevant">
  <div class="child-1 irrelevant">
    Child 1
  </div>
  <div class="child-2 irrelevant">
    Child 2<br> Seems like it works
  </div>
</div>

<div class="container irrelevant">
  <div class="child-1 irrelevant">
    Child 1
  </div>
  <div class="child-2 irrelevant">
    Child 2
    <div class="child-3 irrelevant">
      But it doesn't, child 3 should fill 80% height of the child 2.
    </div>
  </div>
</div>

最佳答案

哦,您可以为此使用 calc。像这样的东西;

.child-2 { height: calc(100vh - 100px); }

假设 .child-1 的固定高度是 100px

如果您想要更动态的东西,请使用@patelarpan 的解决方案,但这既快速又简单(而且不脏)。

关于html - 如何在不使用 flexbox 的情况下让 <div> 填充剩余高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50350971/

相关文章:

javascript - ReactJS:如何将 &lt;input/> 放入 Material UI 的 <TextField/> 中?

javascript - 关于数组的 HTML Javascript。

php - 多级菜单

html - 如何在不改变背景内容的情况下改变背景的不透明度?

javascript - 我如何编写一个函数,如果它的参数是一个 Node 集合,则对 javascript 中的所有 Node 元素执行?

javascript - onLoad 和 onunload 事件未触发

html - 页面上方的页眉滚动 HTML CSS

javascript - Ember 项目中包含外部 JS 文件的路径不正确(不确定)

javascript - 为什么这个随机的、意外的水平线会出现在 IE7 中?

css - 在主表的一行中居中一个表