为何设置flex属性后页脚链接仍无法居中并显示在页面底部
问题根源
现有代码存在三个核心问题,导致效果不符合预期:
- 未给页脚配置定位规则,无法固定在页面底部
- 水平居中属性层级错误:
justify-content: center被加在了宽度由内容撑开的ol元素上,该属性仅在元素宽度占满父容器时才能生效实现居中 - 未清除
ol标签自带的浏览器默认左侧内边距,会造成内容整体偏移
修正代码
替换为以下CSS即可实现「链接横向排列、整体水平居中、固定在页面最底部」的需求:
footer { text-decoration: none; font-size: 1em; /* 固定定位,将页脚钉在视口底部 */ position: fixed; left: 0; bottom: 0; width: 100%; /* 让内部列表水平居中 */ display: flex; justify-content: center; } .footer ol { list-style: none; /* 清除ol默认的内外边距,避免偏移 */ margin: 0; padding: 1em 0; /* 保持链接横向排列 */ display: flex; flex-direction: row; } .footer ol li { margin: 0 1em; } .footer ol li a{ text-decoration: none; } .footer ol li a:hover {color: rgb(83, 54, 150);}
补充:如果你不需要页脚随滚动一直悬浮在视口底部,仅需要它显示在整页内容的最底端,只需把
footer的position: fixed改为position: absolute,同时给body标签添加position: relative; min-height: 100vh; margin: 0;,再给body设置和footer高度一致的padding-bottom,避免页面底部内容被页脚遮挡即可。
内容的提问来源于stack exchange,提问作者Daniel M.
相关产品推荐
相关产品推荐

