2011-05-27 85 views
6

我有一個div向左浮動,div向右浮動,我想要更改背景顏色。它改變了背景,但它在浮動div之前停止。當我將它們取下時,它會繼續保留我想要的正確背景顏色。css,html幫助:左右浮動,關閉背景以擴大div div

<div style='clear:both;border-bottom:3px solid #999;border-top:#333 solid thin;background:#D7E7E8;position:relative;'> 
    <div style='width:1091px;margin:0 auto;margin-top:70px;'> 
     <div style='float:left;width:200px;border:thin solid black;margin-bottom:50px;position:relative;'> 
      float LEFT 
     </div> 
     <div style='float:right;border:thin solid black; width:800px;border:thin solid black;margin-bottom:50px;position:relative;'> 
      float RIGHT 
     </div> 
    </div> 
</div> 

謝謝!

回答

8

您必須清除浮動塊,以便父級環繞它們。

<div style='clear:both;border-bottom:3px solid #999;border-top:#333 solid thin;background:#D7E7E8;position:relative;'> 
    <div style='width:1091px;margin:0 auto;margin-top:70px;'> 
     <div style='float:left;width:200px;border:thin solid black;margin-bottom:50px;position:relative;'> 
      float LEFT 
     </div> 
     <div style='float:right;border:thin solid black; width:800px;border:thin solid black;margin-bottom:50px;position:relative;'> 
      float RIGHT 
     </div> 

     <!--HERE IS THE CLEARING DIV: --> 
     <div style="clear: left;"></div> 
    </div> 
</div> 

您也可以讓父項本身浮動,然後您將不需要額外的標記(清除div)。如果你這樣做,那麼你的父母將需要一個指定的寬度。

說明:

當元件是浮置的,所述親本不知道其高度(除非它是一個浮動元件本身)。你需要在花車下方清楚,以便父母認識到所有孩子的全部身高。

+0

謝謝!我選擇這是正確的答案,因爲我不必亂用doctype!多謝你們! – hellomello 2011-05-27 17:03:30

6

您不需要強制清除浮動 - 只需要爲任何位置定義溢出:相對div。溢出:隱藏和溢出:在沒有任何進一步干預的情況下自動關閉div,從IE6開始。

更改第一行:

<div style='clear:both;border-bottom:3px solid #999;border-top:#333 solid thin;background:#D7E7E8;position:relative; overflow:hidden;'> 

,它會做到同樣的事情,迫使格關閉。

+0

這在IE6中不起作用 – 2011-05-27 09:37:53

+0

我在IE 6.0.2900.2180(XP下的真實IE6,VirtualBox)中測試過它,結果與強制div版本相同。 這可能是你忘了你的DTD - 不要忘了補充: '<!DOCTYPE HTML PUBLIC 「 - // W3C // DTD XHTML 1.0過渡// EN」 \t的「http:// www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd「> 代替普通的舊 – Holland 2011-05-27 11:54:15

+0

doctype在瀏覽器渲染方面非常重要 – 2011-05-27 15:24:26