我正在尝试创建一个可滚动的 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;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
(jsfiddle)
该布局由 flex-parent.container和两个 flex-children 组成:
.heading,具有由padding和定义的固定高度min-height,并且.content这应该占据.heading 空间后的所有剩余空间。为了实现这一点,第一个 flex-child ( .heading) 具有flex: 0 0 auto,第二个 flex-child ( .content) 具有flex: 1 0 auto。但是,我也想.content在里面有可滚动的内容。目前,我认为可以做到这一点的唯一方法是强制.content具有一定程度的固定高度(例如 via max-height,正如我在提供的示例中将其设置为40vh)。但是,虽然它使其可滚动,但它也破坏了 Flexbox 布局,其中content的高度是parent高度减去heading高度。
似乎一旦我指定了.content高度,它就不再尊重弹性盒布局,这是有道理的。但是是否有其他方法可以使其可滚动,同时保留由 Flexbox 布局定义的高度?
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;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5562 次 |
| 最近记录: |