overflow_auto在flex_1的容器失效

2023-02-12,

旧文章从语雀迁移过来,原日期为2022-02-22

我们经常使用flex:1来动态分配父容器剩余空间,这时候如果要在容器上增加滚动条,使用overflow: auto可能会失效

原因:

一般原因:因为容器所在的父容器采用了默认样式overflow: visible,即允许内容溢出到父容器外,那么就会对使用flex: 1的容器没有给到一个固定的高度,所以我们针对这种情况,只需要在父容器添加overflow: auto来让父容器创建BFC,让内容不会溢出。

实例代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
body {
margin: 0;
}
.container {
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
} .parent1 {
height: 80px;
background: red;
} .parent2 {
flex: 1;
display: flex;
flex-direction: column;
/* 父容器创建BFC,一般使用overflow:auto */
overflow: auto;
} .child1 {
height: 80px;
background: green;
} .child2 {
flex: 1;
overflow: auto;
background: greenyellow;
} .child2-sub {
height: 1000px;
width: 100px;
background: orange;
}
</style>
<body>
<div class="container">
<div class="parent1"></div>
<div class="parent2">
<div class="child1"></div>
<div class="child2">
<div class="child2-sub"></div>
</div>
</div>
</div>
</body>
</html>

overflow_auto在flex_1的容器失效的相关教程结束。

《overflow_auto在flex_1的容器失效.doc》

下载本文的Word格式文档,以方便收藏与打印。