为Footer添加背景与边框后与上方内容重叠,如何解决?
问题根源很明确:你用了**浮动(float)**布局,但清除浮动的样式没有生效。CSS里写的是.outer::after(类选择器),但HTML中的父容器是id="outer",两者不匹配,导致outer容器无法包裹住浮动的子元素,footer就会往上挤占浮动元素的位置。
方案一:修正清除浮动的选择器
把CSS中的类选择器.outer改成ID选择器#outer,让清除浮动的样式作用到正确的容器上:
.inner { width: 50%; float: left; padding: 12px; box-sizing: border-box; } #outer::after { /* 这里把.改成# */ content: ""; display: table; clear: both; } #footer { text-align: center; background-color: rgb(213, 209, 209); padding: 12px; margin-top: 10px; }
方案二:用overflow属性清除浮动
另一种更简单的方式是给#outer添加overflow: auto,让容器自动包裹住内部的浮动元素:
.inner { width: 50%; float: left; padding: 12px; box-sizing: border-box; } #outer { overflow: auto; /* 添加这个属性 */ } #footer { text-align: center; background-color: rgb(213, 209, 209); padding: 12px; margin-top: 10px; }
两种方案都能让outer容器正常占据空间,footer就会和上方内容完全独立,各自应用样式。
内容的提问来源于stack exchange,提问作者Aditya Tripathi
相关产品推荐
相关产品推荐

