【问题标题】:Scrollable flex child with flex-grow 1带有 flex-grow 1 的可滚动 flex 子节点
【发布时间】:2019-05-12 02:48:43
【问题描述】:

我正在尝试创建一个可滚动的 flex-child,其高度由其 flex-grow 属性决定。

例子:

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

.heading {
  background: #9D8189;
  flex: 0 0 auto;
  padding: 2rem;
  min-height: 10rem;
}

.content {
  background: #FFE5D9;
  flex: 1 0 auto;
  padding: 2rem;
  /* Makes it scrollable but breaks the flexbox layout */
  max-height: 40vh;
  overflow: scroll;
}

.box {
  background: #D8E2DC;
  padding: 7rem;
}
<body>
  <div class="container">
    <div class="heading">heading</div>
    <div class="content">
      <div class="box">box1</div>
      <div class="box">box2</div>
      <div class="box">box3</div>
    </div>
  </div>
</body>

(jsfiddle)

布局由 flex-parent .container 和两个 flex-children 组成:

  • .heading,具有由paddingmin-height 定义的固定高度,以及
  • .content 应该占用.heading 空间之后的所有剩余空间。为了实现这一点,第一个 flex-child (.heading) 具有 flex: 0 0 auto,第二个 flex-child (.content) 具有 flex: 1 0 auto

不过,我还希望.content 里面有可滚动的内容。目前,我认为我能做到的唯一方法是强制.content 具有某种固定的高度(例如,通过max-height,正如我在提供的示例中所做的那样,将其设置为40vh)。但是虽然它可以滚动,但它也破坏了 flexbox 布局,其中content 的高度是parent 高度减去heading 高度。

似乎只要我指定.content 高度,它就会停止尊重弹性盒布局,这是有道理的。但是有没有其他方法可以让它在保持由 flexbox 布局定义的高度的同时可滚动?

【问题讨论】:

    标签: css flexbox


    【解决方案1】:

    height:100% 需要计算来自父级的已知height,除非该元素本身是HTML。 你需要:html, body, {height:100%} 所以.container {height:100%} 的含义是,height 值将从HTML(浏览器窗口)继承,然后是BODY,最后是.container

    也可以使用VH 代替% 来简化操作。

    .container 应设置为 overflow:hidden 以允许子级在达到父级限制时滚动。

    代码示例:

    * {
      box-sizing: border-box;
      padding: 0;
      margin: 0;
    }
    
    .container {
      display: flex;
      flex-direction: column;
      height: 100vh;/* update */
      overflow:hidden;/* update */
    }
    
    .heading {
      background: #9D8189;
      /*flex: 0 0 auto; */
      padding: 2rem;
      min-height: 10rem;/* if needed */
    }
    
    .content {
      background: #FFE5D9;
      flex: 1 ;/* make it simple */
      padding: 2rem;
      overflow: auto;/* scroll if needed */
    }
    
    .box {
      background: #D8E2DC;
      padding: 7rem;
    }
      <div class="container">
        <div class="heading">heading</div>
        <div class="content">
          <div class="box">box1</div>
          <div class="box">box2</div>
          <div class="box">box3</div>
          <div class="box">box3</div>
        </div>
      </div>

    【讨论】:

      【解决方案2】:

      min-height: 0 设置为 .content 类样式,它应该可以正常工作

      【讨论】:

        猜你喜欢
        • 2020-01-15
        • 2017-06-15
        • 1970-01-01
        • 2023-01-05
        • 2018-03-30
        • 2021-08-12
        • 2018-03-09
        • 2019-05-27
        • 1970-01-01
        相关资源
        最近更新 更多