我们经常使用flex:1来动态分配父容器剩余空间,这时候如果要在容器上增加滚动条,使用overflow: auto可能会失效。
原因:
一般原因:因为容器所在的父容器采用了默认样式overflow: visible,即允许内容溢出到父容器外,那么就会对使用flex: 1的容器没有给到一个固定的高度,所以我们针对这种情况,只需要在父容器添加overflow: auto来让父容器创建BFC,让内容不会溢出。
实例代码
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| <!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; 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>
|