解决办法:
加上 flex: 1 0 auto; height: 0(纵向滚动);
或 flex: 1 0 auto; width: 0(横向滚动);
背景:在项目开发过程中有固定头部,内容部分占据剩余空间的上下布局结构。
理想情况内容部分向下滚动后头部固定不动。
html
1
2
3
4
5
6
7
8
9
10 <body>
<div class="page">
<header>固定的头部</header>
<div class="content">
<div class="content-box">
想要内部滚动的内容部分
</div>
</div>
</div>
</body>
css
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 html, body, .page {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.page {
display: flex;
flex-direction: column;
}
header {
background: #4dc7ec;
line-height: 60px;
}
.content {
flex: 1;
overflow-y: auto;
color: white;
background: #0000ff;
}
.content-box {
height: 2000px;
}
这种情况是能实现上面的效果的,因为.page的父元素的height是固定值。
我们如果把.page的父元素body改成flex的情况就会不一样了。(注意:这里是为了演示,实际项目中body你可能不会弄成flex的。但是你有可能flex里面套用flex)
css
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
32
33 html, body, .page {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
body {
display: flex;
flex-direction: column;
}
.page {
display: flex;
flex: 1;
flex-direction: column;
}
header {
background: #4dc7ec;
line-height: 60px;
}
.content {
flex: 1;
overflow-y: auto;
color: white;
background: #0000ff;
}
.content-box {
height: 2000px;
}
效果如下:
头部固定失效了。
怎么解决呢?
1 2 3 4 5 6 | .content { flex: 1 0 auto; height: 0; .... } height设为0,如果横向滚动width设为0,flex-shrink设为0 |
css
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
32 html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
body{
display: flex;
flex-direction: column;
}
.page {
display: flex;
flex: 1;
flex-direction: column;
}
header {
background: #4dc7ec;
line-height: 60px;
}
.content {
flex: 1 0 auto;
height: 0;
overflow-y: auto;
color: white;
background: #0000ff;
}
.content-box {
height: 2000px;
}