2012-10-29 84 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