CSS 背景颜色对 DIV 没有影响

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/944663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 20:39:32  来源:igfitidea点击:

CSS background-color has no effect on a DIV

css

提问by Alec Smart

你好,世界

Why does the background color not show as black? I cannot set the width and float, is it possible without them?

为什么背景颜色不显示为黑色?我无法设置宽度和浮动,没有它们可以吗?

Thank you for your time.

感谢您的时间。

回答by Lobstrosity

Since the outer div only contains floated divs, it renders with 0 height. Either give it a height or set its overflow to hidden.

由于外部 div 仅包含浮动 div,因此它以 0 高度呈现。要么给它一个高度,要么将它的溢出设置为隐藏。

回答by cletus

Change it to:

将其更改为:

<div style="background-color:black; overflow:hidden;" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>

Basically the outer div only contains floats. Floats are removed from the normal flow. As such the outer div really contains nothing and thus has no height. It really is black but you just can't see it.

基本上外部 div 只包含浮点数。浮标从正常流中移除。因此,外部 div 确实不包含任何内容,因此没有高度。它确实是黑色的,但你只是看不到它。

The overflow:hidden property basically makes the outer div enclose the floats. The other way to do this is:

overflow:hidden 属性基本上使外部 div 包含浮动。另一种方法是:

<div style="background-color:black" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
<div style="clear:both></div>
</div>

Oh and just for completeness, you should really prefer classes to direct CSS styles.

哦,为了完整起见,您真的应该更喜欢类来指导 CSS 样式。

回答by PatrikAkerstrand

Without floats (and unneccessary divs):

没有浮点数(和不必要的 div):

<div style="background-color:black;" onmouseover="this.bgColor='white'">
    hello world
</div>

If you use floats, you have to float the outer div and specify widths.

如果使用浮动,则必须浮动外部 div 并指定宽度。

回答by Emily

Floats don't have a height so the containing div has a height of zero.

浮点数没有高度,因此包含的 div 的高度为零。

<div style="background-color:black; overflow:hidden;zoom:1" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>

overflow:hidden clears the float for most browsers.

overflow:hidden 清除大多数浏览器的浮动。

zoom:1 clears the float for IE.

zoom:1 清除 IE 的浮动。

回答by bicbmx

This being a very old question but worth adding that I have just had a similar issue where a background colour on a footerelement in my case didn't show. I added a position: relativewhich worked.

这是一个非常古老的问题,但值得补充的是,我刚刚遇到了一个类似的问题,footer我的案例中元素的背景颜色没有显示。我添加了一个position: relative有效的。