本文使用flex布局,实现下面的效果,其中三个绿色的盒子中可以实现超出滚动,且相互不会影响,如下图:
一、dom结构
<div class="icd-container">
<div class="icd-header"></div>
<div class="icd-body">
<div class="top-card"></div>
<div class="main-card">
<div class="alarm-list">高级布局...</div>
<div class="sign-data-container">高级布局...</div>
<div class="sleep-data-container"> 高级布局...</div>
</div>
</div>
</div>
二、css代码
.icd-container {
margin: 0 auto;
display: flex;
flex-direction: column;
width: 94%;
height: 100%;
border: 1px solid red;
.icd-header {
width: 100%;
height: 60px;
// flex:none => 元素不会放大或缩小,初始大小是根据内容自动计算的,在此为60px
// flex-grow:0; flex-shrink:0; flex-basis:auto
flex: none;
background-color: rgb(240, 95, 12);
}
.icd-body {
flex: 1;
height: 0;
display: flex;
flex-direction: column;
border: 1px solid yellow;
.top-card {
width: 100%;
height: 100px;
flex: none;
background-color: rgb(211, 14, 73);
}
.main-card {
flex: 1;
height: 0;
margin-top: 12px;
display: flex;
flex-direction: row;
justify-content: space-between;
border: 1px solid blue;
.box-left,
.box-middle,
.box-right {
width: 33%;
overflow: auto;
padding: 12px 10px;
background-color: rgb(84, 205, 36);
// 隐藏滚动条
&::-webkit-scrollbar {
display: none; // Chrome, Safari, Edge
}
-ms-overflow-style: none; // IE, Edge
}
}
}
}
三、重点分析
1. flex: none + 固定高度
-
flex: none 确保该元素不会被flex容器的伸缩影响
-
元素将严格保持其设定的高度(60px)
-
防止其他设置了 flex: 1 的元素挤压这个固定高度的元素
.icd-container {
//父级设置flex
display: flex;
flex-direction: column;
height: 100%;
...
}
.icd-header {
//第一个子元素定高
height: 60px;
//flex:none => 元素不会放大或缩小,不会受flex:1影响, 固定为60px
flex: none;
...
}
.icd-body {
//第二个元素相当于设置了flex:1 1 0%;即会自动伸缩,内容过多会将第一个定高的元素撑掉
flex: 1;
...
}
2.flex:1 + height:0
-
flex: 1让元素占据容器中所有剩余空间 -
height: 0的设置很关键,它有两个作用: -
确保元素的初始高度为0,让flex完全控制实际高度
-
防止内容超出时撑大容器,配合
overflow: auto可以实现内部滚动
.icd-body {
flex: 1; // 相当于 flex: 1 1 0%
height: 0;
// ... 其他代码 ...
}
这种组合在实现类似固定头部+可滚动内容区域的布局时特别有用,可以保证:
-
固定部分保持不变
-
可伸缩部分能够自适应剩余空间
-
内容过多时可以在各自的区域内滚动,而不会影响整体布局