【问题标题】:How do I make a div stretch in a flexbox of dynamic height?如何在动态高度的 flexbox 中进行 div 拉伸?
【发布时间】:2017-01-05 04:51:59
【问题描述】:

我正在尝试使用 flexbox 进行堆叠布局。理想情况下应该是这样的:

底部(蓝色)div 的固定高度为250px,顶部div 为n-250,其中n 是父容器的大小——换句话说,顶部应该拉伸以填充容器。

当我有容器高度时,我对如何执行此操作有一些想法,但我宁愿避免在运行时确定该变量。

这个问题已经以各种形式详细讨论过,但似乎没有一个解决这个简单的用例(例如,here 与页眉/内容/页脚一起使用,但表面上不只是与内容/页脚一起使用) .

我已经设置了codepen with the example

【问题讨论】:

  • 为什么这比顶部 div 上的 flex-grow 更复杂?
  • FYI 在您的代码笔中,您的 HTML 中有 2 个错误阻止它工作。 而不是
    和 bottom="bottom" 而不是 id="bottom"
  • 如果容器的高度未知或无法解析(例如,固定值),那么通常您不能。请注意,以下所有当前答案都要求知道容器的高度。如果不是...他们将无法正常工作。
  • 标签: css flexbox


    【解决方案1】:

    我认为这是使用flex-grow: 1; 回答您的问题。希望对你有帮助

    https://jsfiddle.net/BradChelly/ck72re3a/

    .container {
      width: 100px;
      height: 150px;
      background: #444;
      display: flex;
      flex-direction: column;
      align-content: stretch;
    }
    .box1 {
      width: 100%;
      background: steelblue;
      flex-grow: 1;
    }
    .box2 {
      height: 50px;
      width: 100%;
      background: indianred;
    }
    <div class="container">
      <div class="box1"></div>
      <div class="box2"></div>
    </div>

    【讨论】:

    • 我知道...仍然很糟糕,甚至 Crayola 都摆脱了“肉”和“印度红”
    【解决方案2】:

    最少的代码行。 布拉德的答案是正确的。但是这里我使用flex而不是flex-grow并删除了align-items

    .container {
      width: 100px;
      height: 100vh;
      display: flex;
      flex-direction: column;
    }
    .top {
      width: 100%;
      background: blue;
      flex: 1;
    }
    .bottom {
      height: 70px;
      width: 100%;
      background: green;
    }
    <div class="container">
      <div class="top"></div>
      <div class="bottom"></div>
    </div>

    Demo在这里

    【讨论】:

    • 使用flex而不是flex-grow的原因是什么?
    • 简写,比如border而不是border-color
    【解决方案3】:

    不用flexbox也可以做到这一点,只需使用CSS Calc即可

    html, body {
      margin: 0;
    }
    .container {
      height: 100vh;
    }
    .top {
      background: lightblue;
      height: calc(100% - 100px);
    }
    .bottom {
      height: 100px;
      background: lightgreen;
    }
    <div class="container">
      <div class="top"></div>
      <div class="bottom"></div>
    </div>

    如果您希望它在旧版浏览器上运行,请像这样更新这些规则

    html, body {
      margin: 0;
      height: 100%;
    }
    .container {
      height: 100%;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-25
      • 2017-10-19
      • 1970-01-01
      • 2018-01-03
      • 2013-07-27
      • 2019-12-13
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多