overflow滚动遇到flex失效问题解决

解决办法:

加上 flex: 1 0 auto; height: 0(纵向滚动);

或 flex: 1 0 auto; width: 0(横向滚动);

背景:在项目开发过程中有固定头部,内容部分占据剩余空间的上下布局结构。

理想情况

理想情况内容部分向下滚动后头部固定不动。

html

<body>
<div class="page">
  <header>固定的头部</header>
  <div class="content">
    <div class="content-box">
      想要内部滚动的内容部分
    </div>
  </div>
</div>
</body>

 css

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

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;
}

 效果如下:

 

实际效果头部固定失效了。

怎么解决呢?

.content {
  flex: 1 0 auto;
  height: 0;
  ....
}
height设为0,如果横向滚动width设为0,flex-shrink设为0

 css

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;
} 
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值