核心逻辑:html/body设置高度100%,主体内容区域设置min-height:100%,内容区域通过padding-bottom预留页脚区域高度,页脚区域通过margin-top或者position,移动到预留区域上层。这样就可以实现页面内容不足时,页脚始终位于页面底部,页面内容超出后,页脚随着页面滚动,变成正常流体布局。
方法1
html/body设置高度100%,页面主体部分设置最小高度为100%,设置padding-bottom:300px(footer部分高度),预留footer高度,footer设置margin-top:-300px(footer移动到主体部分给预留的高度),主体内容不足100%时,由于设置了min-height:100%,所以footer会自动位于页面最底部,内容超出后,footer会跟随页面高度滚动。
<html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> html, body { height: 100%; margin: 0; padding: 0; } .page { box-sizing: border-box; /*为元素指定的任何内边距和边框都将在已设定的宽度和高度内进行绘制*/ min-height: 100%; padding-bottom: 300px; background: #f5f5f5; } footer { height: 300px; margin-top: -300px; opacity: 0.5; background: #9999; } </style></head><body> <div class="page"> 主要页面 </div> <footer>底部</footer></body></html>
方法2
主要通过position定位把页脚区域定位到页面底部,这种方法页面结构会多一层。
<html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> html, body { height: 100%; margin: 0; padding: 0; } .page-container { position: relative; min-height: 100%; } .page-main { padding-bottom: 300px; } footer { position: absolute; left: 0; bottom: 0; height: 300px; } </style></head><body> <div class="page-container"> <div class="page-main"> 主要页面 </div> <footer>底部</footer> </div></body></html>