css实现上中下布局(上下固定,中间自适应)

深藏阁楼爱情的钟 2023-01-14 14:58 199阅读 0赞

先上效果图:

在这里插入图片描述

实现方法:

方法一:

这个最简单,利用css中vh单位和calc() 函数

使用场景:

页面布局

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>css上中下布局</title>
  8. <style> body { margin: 0; padding: 0; } .top { height: 100px; background: red; } .center { height: calc(100vh - 200px); background: yellow; } .bottom { height: 100px; background: red; } </style>
  9. </head>
  10. <body>
  11. <div class="top"></div>
  12. <div class="center"></div>
  13. <div class="bottom"></div>
  14. </body>
  15. </html>

方法二

利用css定位属性

使用场景:

一般用于某些元素根据屏幕大小适配,这个弹窗上下部分固定,中间部分需要自适应高度时

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>css上中下布局</title>
  8. <style> body { margin: 0; padding: 0; } .top { position: absolute; top: 0; width: 100%; height: 100px; background: red; } .center { position: absolute; top: 100px; bottom: 100px; width: 100%; height: auto; background: yellow; } .bottom { position: absolute; height: 100px; width: 100%; bottom: 0; background: red; } </style>
  9. </head>
  10. <body>
  11. <div class="top"></div>
  12. <div class="center"></div>
  13. <div class="bottom"></div>
  14. </body>
  15. </html>

方法三

使用flex布局,这个时候父元素一定要给高度

使用场景:

同方法二

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>css上中下布局</title>
  8. <style> body { margin: 0; padding: 0; display: flex; flex-direction: column; /* 父元素一定要给高度 */ height: 100vh; } .top { width: 100%; height: 100px; background: red; } .center { width: 100%; flex: 1; background: yellow; } .bottom { width: 100%; height: 100px; background: red; } </style>
  9. </head>
  10. <body>
  11. <div class="top"></div>
  12. <div class="center"></div>
  13. <div class="bottom"></div>
  14. </body>
  15. </html>

应该还有很多实现的方法,目前我常用的就是这几种,有更好的方案的同学可以一起交流。

个人水平有限,有问题欢迎大家留言指导,仅供学习和参考。

学海无涯!努力二字,共勉!

发表评论

表情:
评论列表 (有 0 条评论,199人围观)

还没有评论,来说两句吧...

相关阅读