如何去除Footer左右及底部的空白区域
我制作了一个footer,但无法去除其左侧、右侧及底部的空白区域。相关代码如下:
HTML代码
<footer id="footerID" class="footer"> <a href="https://www.linkedin.com/home?originalSubdomain=pt" target="_blank" >LinkedIn</a > <a href="https://mail.google.com/mail/u/0/" target="_blank">Gmail</a> <a href="https://github.com/" target="_blank">GitHub</a> </footer>
CSS代码
.footer{ width: 100%; background-color: #64ffc6; color: white; text-align: center; } .footer > a{ display: inline-block; text-align: center; padding: 10px 30px 10px 30px; font-weight: bold; color:#182436; font-size: 15px; text-decoration: none; }
问题原因
空白来自两个地方:一是浏览器默认给body元素添加了margin值,导致footer左右出现留白;二是如果页面内容高度不足视口高度,footer无法贴底,会出现底部空白。
解决方案
修改CSS,添加全局样式重置和布局调整:
/* 重置所有元素的默认margin和padding,消除浏览器自带样式干扰 */ * { margin: 0; padding: 0; box-sizing: border-box; } /* 让body占满视口高度,用flex布局实现footer固定贴底 */ body { min-height: 100vh; display: flex; flex-direction: column; } .footer{ width: 100%; background-color: #64ffc6; color: white; text-align: center; margin-top: auto; /* 自动填充上方剩余空间,强制footer贴底 */ } .footer > a{ display: inline-block; text-align: center; padding: 10px 30px; font-weight: bold; color:#182436; font-size: 15px; text-decoration: none; }
关键说明
- 全局样式重置:用
*选择器清除所有元素的默认边距,彻底解决body默认margin导致的左右留白问题。 box-sizing: border-box:确保footer的width:100%不会因为padding或border超出父容器宽度,避免隐性留白。- flex布局+
margin-top: auto:不管页面内容多少,都能让footer固定在页面底部,同时消除底部空白。
内容的提问来源于stack exchange,提问作者Alexandre Gomes
相关产品推荐
相关产品推荐

