2014-03-25 44 views
0

我需要顯示兩個彼此相鄰且具有不同背景的<div>Div在浮動後不會顯示背景顏色:左邊

不幸的是,第二個<div>background-color被忽略。我已閱讀了一些帖子,並且人們建議添加clear:both;。不幸的是,這並沒有幫助。有沒有辦法如何獲得background-color.div2

CSS:

.div1 { 
    margin-top:10px; 
    float:left; 
    background:blue; 
    width:382px; 
    padding:0 5px 10px 10px; 
} 
.div2 { 
    margin-top:10px; 
    width:374px; 
    background:red; 
    padding:0 10px 10px 0; 
} 
.clear { 
    clear:both; 
} 

HTML:

<div class="div1">DIV1</div> 
<div class="div2">DIV2</div> 
<div class="clear"></div> 

回答

0

好吧,我認爲我瞭解你的問題。你想要的元素相鄰。

這裏是這樣的CSS:

.div1 { 
    float:left; 
    background:blue; 
    width:382px; 
    padding:0 5px 10px 10px; 

} 
.div2 { 
    /* div1 will follow this */ 
    margin-top:10px; 
    /* width of div1 + it's paddings */ 
    margin-left:397px; 
    width:374px; 
    background:red; 
    padding:0 10px 10px 0; 
} 
.clear { 
    clear:both; 
} 

這裏是一個演示:http://jsfiddle.net/rvuyH/2/

0

只需添加浮動:左爲DIV2 CSS像下面顯示彼此相鄰的背景顏色都div的

.div2{margin-top:10px;width:374px;float:left;background:green;padding:0 10px 10px 0;} 
0

我剛纔已經改變了由@給出的代碼user3401335

JS FIDDLE DEMO。請檢查出來

HTML:

<div class="div1">DIV1</div> 
<div class="div2">DIV2</div> 
<div class="clear"></div> 

CSS:

.div1 { 
    margin-top:10px; 
    float:left; 
    background:blue; 
    width:50%; 
    padding:0 5px 10px 10px; 
} 
.div2 { 
    margin-top:10px; 
    width:45%; 
    background:red; 
    padding:0 10px 10px 0; 
    float:left; 
}