这里有我div的完整示例。
为什么footer
没有从父元素(container
)继承背景颜色?
这里有我div的完整示例。
为什么footer
没有从父元素(container
)继承背景颜色?
float
时,它就像与父元素断开连接一样。因此,无法继承inherit
的值。此外,父元素停止扩展到子元素的高度。去掉float
后,您可以看到它正常工作。float
,您需要在footer
上放置background-color
。footer
后面再放置另一个<div style="clear: both"></div>
,如另一个答案所示,但这只是一个技巧,以使父元素能够跟随子元素的高度。您需要清除浮动的 div:http://jsfiddle.net/74MvW/14/
<div />
。一些浏览器会不喜欢它来阻塞元素。 - user736619它没有获取背景颜色,因为“container” div 具有背景,但是“footer” div 是向左浮动的,这意味着它不会影响“container” div 的高度。
您必须要么去掉浮动,要么在 footer div 后面添加一个 clearer div,就像这样:
<div class="container">
<div class="footer">
Hello
</div>
<div style="clear:both;float:none;"><!-- Clearer --></div>
</div>
正如其他答案所提到的,问题在于float
值。解决这个问题最好的方法是将.footer
div设置为“inherit”,继承父元素的背景:
.footer {width:910px; height:150px; float:left; background: inherit}
演示。
一些 CSS 属性默认是继承的(例如 font-family
);其他具有默认属性。在 background-color
的情况下,默认值为 transparent
。如果您希望该属性被继承,必须明确说明。