关于CSS:具有flex-grow 1的可滚动flex子元素

Scrollable flex child with flex-grow 1

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

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
.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;
}
1
2
3
4
5
6
7
8
9
10
<body>
 
    heading
   
      box1
      box2
      box3
   
 
</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布局,这是有道理的。但是还有其他方法可以使其在保持其高度(由flexbox布局定义)的同时滚动吗?


height:100%要求从父级开始计算已知的height,除非元素本身是HTML
您需要:html, body, {height:100%},因此.container {height:100%}的含义是,height的值将继承自HTML(浏览器的窗口),然后继承自BODY,最后是.container

也可以使用

VH代替%来简化它。

.container应该设置为overflow:hidden,以使子级一旦达到父级的限制即可滚动。

代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
* {
  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;
}
1
2
3
4
5
6
    heading
   
      box1
      box2
      box3
      box3


min-height: 0设置为。content类样式,它应该可以按您期望的方式运行