先上一个效果图,使用的是flex多层嵌套,当父元素设置flex-direction: column并且子元素设置flex:1的时候,这个自适应高度的模块如何实现垂直滚动:
先上效果图:
这里我的滚动区域是一个聊天窗口,下面是代码的实现
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 63 64 65 66 67 68 69 70 |
<!DOCTYPE html> <html> <head> <title>222</title> </head> <style> html, body { margin: 0; padding: 0; width: 100%; height: 100%; } .container { width: 100%; height: 100%; margin: 0 auto; } .flex { display: flex; } .flex-direction { flex-direction: column; } .flex-sub { flex: 1; } .bg-red { background: red; } .bg-green { background: green; } .bg-orange { background: orange; } .bg-black { background: black; } .bg-pink { background: pink; } .h50 { height: 50px; } .w200 { width: 200px; } </style> <body> <div class="container flex flex-direction"> <div class="main flex-sub bg-red flex"> <div class="main-left w200">left</div> <div class="main-right flex-sub flex flex-direction"> <div class="main-right-header bg-orange h50">header</div> <div class="main-right-body flex-sub bg-black flex"> <div class="main-right-body-left flex-sub flex flex-direction"> <div class="content bg-green flex-sub" style=" overflow: auto; max-height: calc(100vh - 300px);"> 在这里你可以添加很多文字来实现滚动 </div> <div class="textarea" style="height: 200px">textarea</div> </div> <div class="main-right-body-right w200 bg-pink">right</div> </div> </div> </div> <div class="footer bg-green h50">footer</div> </div> </body> </html> |
重要的是理解css calc函数的功能以及单位属性vh,这里有相关介绍:
calc: https://blog.csdn.net/romantic_love/article/details/80868909