2012-10-29 82 views
6

我将外部div的背景颜色设置为蓝色,但不显示。为什么?CSS背景色不起作用

CSS

.question-template { 
    width: auto; 
    height: auto; 
    background-color: blue; 
} 
.question { 
    float: left; 
    margin: 10px; 
} 
.participants { 
    background-color: green; 
    float: left; 
    margin: 10px; 
}​ 

HTML

<body> 
<div class="question-template"> 
    <div class="participants">234</div> 
    <div class="question">Some lorem ipsum text</div> 
</div> 
</body> 

它的一个演示http://jsfiddle.net/4zjtp/

回答

4

尝试这样的..

.question-template { 
    width: auto; 
    height: auto; 
    background-color: blue; 
    overflow:auto; 
} 
+0

当我指定的问题模板的宽度和增加问题的长度,文本低于参与者分区。我怎样才能让它保持在同一条线上? – SamB

+0

您可以使用 display:inline-block。 – Xavier

+0

似乎没有工作。 http://jsfiddle.net/4zjtp/15/ – SamB

2

Live demo ........... 嗨现在定义parent div.question-template overflow:hidden;

.question-template{ 
overflow:hidden; 
} 

方法二

现在很清楚你的父母

的CSS

.clr{ 
clear:both; 
} 

HTML

<div class="question-template"> 
<div class="participants">234</div> 
<div class="question">Some lorem ipsum text</div> 
    <div class="clr"></div> 
</div> 

Live demo

4

这是因为无论你的子元素向左浮动。这意味着容器不会拉伸到包含子元素所需的全部高度。

为了解决这个问题,你需要添加clearfix类,如这对你的CSS:

.clearfix:after { 
    content: ""; 
    display: table; 
    clear: both; 
} 

然后将该类添加到您的HTML这样的:

<div class="question-template clearfix"> 

在这里看到更多信息:http://css-tricks.com/snippets/css/clear-fix/

1

您需要在父div上应用清除浮点数以确保它占据内部元素。 您可以在父项关闭之前插入<div style="clear:left;"></div>,也可以在父div上应用clearfix类。

.clearfix:after { 
    content: "."; 
    display: block; 
    clear: both; 
    visibility: hidden; 
    line-height: 0; 
    height: 0; 
} 

.clearfix { 
    display: inline-block; 
} 

html[xmlns] .clearfix { 
    display: block; 
} 

* html .clearfix { 
    height: 1%; 
} 
​ 

然后你只需添加clearfix类父DIV现在

...  
<div class="question-template clearfix"> 
... 

Working Example