使 div 展开以占用所有可用空间

use*_*474 5 html javascript css

我想要一个类似桌面的全页宽度布局。顶部的一些菜单(未知高度,取决于内容)和下方的 div 占据视口中的所有可用空间。

div {
  padding: 0px
}

html,
body {
  height: 100%;
  padding: 0px;
  margin: 0px;
}

.outer {
  background: olive;
  height: 100%;
}

.menu {
  background: orange;
}

.should_fill_available_space {
  background: brown;
}
Run Code Online (Sandbox Code Playgroud)
<div class="outer">
  <div class="menu">
    Lorem Ipsum Lorem Ipsum Lorem Ipsum
  </div>
  <div id="this" class="should_fill_available_space">
    Brown color should go all the way down
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我有一个用于这种情况的代码笔:https ://codepen.io/marek-zganiacz/pen/NvEaxr

我想should_fill_available_space一直往下走,就像在那里menuheight:10%should_fill_available_space有“高度:90%”的情况一样。

RMo*_*RMo 8

实现这一点的最简单方法是使用 Flexbox。

  1. 您分配display: flex给父容器。在你的情况下,这是外部的.outer
  2. Flexbox 在单一方向上工作。因此,您可以将它们视为列(垂直)或行(水平)。默认设置是将子元素分布在一行上。但我们想创建一个专栏。因此我们必须将flex-directionon更改.outerflex-direction: column.
  3. 现在我们需要指定 Flexbox 如何划分.outer. 正常行为是弹性盒为其子项提供正常的宽度/高度。但通过分配flex:1.should_fill_available_space,该元素将获得所有额外的可用空间。Flexbox 基本上说的是,我们希望计算机使用所有 1/1 = 100%(使用的 Flex 值除以所有子项的总 Flex 值)可用空间来应用于.should_fill_available_space,同时保持最小的宽度空间.menu。从技术上讲flex:,它是其他一些属性的简写,但这对于这个问题来说并不重要。

这是你的 JS-Fiddle:https://jsfiddle.net/cryh53L7/

html

<div class="outer">
  <div class="menu">
    Lorem Ipsum
    Lorem Ipsum
    Lorem Ipsum
  </div>
  <div id="this" class="should_fill_available_space">
    Brown color should go all the way down
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

 div{
      padding: 0px
    }
    html, body{
      height: 100%;
      padding: 0px;
      margin: 0px;
    }
    .outer {
      display: flex;
      flex-direction: column;
      background: olive;
      height: 100%;
    }
    .menu{
      background: orange;

    }
    .should_fill_available_space{
      flex: 1;
      background: brown;

    }
Run Code Online (Sandbox Code Playgroud)