网站Footer导航完美自动固定在底部div+css,为啥要添加完美呢?因为马上过年,我们需要一个比今年更完美一点
我们在设计网页的时候,都会遇到一个问题:
我底部导航要在底部,用position: absolute;定位的话,底部导航应该就连接在了内容的最后。如果内容够长超出屏幕效果还是比较理想的。如果内容比较短,那么footer导航直接在半中间。
随后我们就想到了一点,直接用position: fixed;不就好了吗?这样直接永远固定在底部,木有错,这样确实永远固定在了底部,只有中间内容在滑动,这也不是很理想。其实我们实际需要的效果应该是这样的:
内容少时:固定在底部
内容超出时:连接在内容底部,滑动到内容结束在显示
大部分都是用js去处理的,但是css也是可以的哦!
原理解释
1.分析:我们把网看成3部分,头部,内容,尾巴。分别写3个div
2.设置内容高度:
首先给html一个高度为100%
* { padding: 0; margin: 0; } html { height: 100%; }
body我们给一个最小的高度为100%和定位,footer基于body定位这样的话 即使内容短footer导航也能固定在底部,内容超出也会连接在下方
body { min-height: 100%; position: relative; }
代码演示:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>1</title> <style> * { padding: 0; margin: 0; } html { height: 100%; } body { min-height: 100%; position: relative; } .footer { height: 100px; line-height: 100px; background: #8f7af9; width: 100%; position: absolute; bottom: 0; left: 0; color: #FFFFFF; text-align: center; font-size: 30px; font-weight: bold; } .feng { padding-bottom: 130px; } .rui { height: 200px; line-height: 200px; background-color: #4489ca; text-align: center; color: #FFFFFF; width: 80%; margin-top: 30px; margin-left: 10%; } .head { height: 100px; line-height: 100px; background: #ef7373; width: 100%; color: #FFFFFF; text-align: center; font-size: 30px; font-weight: bold; } </style> </head> <body> <div class="head"> 我是headder </div> <div class="feng"> <div class="rui"> 我是一个内容 </div> <div class="rui"> 我是一个内容 </div> <!-- 取消注释预览效果 --> <!-- <div class="rui"> 我是一个内容 </div> <div class="rui"> 我是一个内容 </div> <div class="rui"> 我是一个内容 </div> --> </div> <div class="footer"> 我是footer </div> </body> </html>