2011-04-26 65 views

回答

9

您可以使用float CSS樣式。將其設置爲left爲第一個div。第二格將被放置恰到好處的它(只要有足夠的空間)

<div> 
    <div style="float: left"> 
    <p> This div will be on the left</p> 
    </div> 
    <div > 
    <p> This div will be on the right</p> 
    </div> 
    <!-- optionally, you may need to add a "clearance" element below the floating divs --> 
    <div style="clear: both" ></div> 
</div> 

注意,有時可能需要以得到浮動,以實現適當的水平佈局的div固定寬度。

<div> 
    <div style="width: 100px; float: left"> 
    <p> 100px div will be on the left</p> 
    </div> 
    <div style="width: 200px"> 
    <p> 200px div will be on the right as long as there is enough 
     horizontal space in the container div 
    </p> 
    </div> 
    <!-- optionally, you may need to add a "clearance" element below the floating divs --> 
    <div style="clear: both" ></div> 
</div> 
2

最簡單的辦法就是CSS的float:

<div id="div1">hello</div> 
<div id="div2">world</div> 

而CSS:

#div1 {float: left;} 
#div2 {float: left; margin-left: 10px;} 

Simple test case

浮動的div後再添一個清除浮動,以便進一步內容將被罰款顯示:

<div style="clear: both;"></div> 
4
<div> 
    <div style="float:left;"></div> 
    <div style="float:left;"></div> 
    <div style="clear:both;"><!-- usually leave this empty --></div> 
</div> 

您也可以浮動:權利;爲了使div對齊在頁面的右側。清楚是非常重要的。在IE中,很多時候,浮動左/右規則會傳播到其他元素,而不是您打算浮動的元素。儘管如此,你不會馬上接受它,它會成爲一個噩夢,弄清楚爲什麼你的網頁看起來像垃圾一樣。所以,只要養成一個空的清晰div作爲你決定浮動的任何div的最後一個兄弟的習慣。

+1

明確:兩者都是重要細節。 – ThatBlairGuy 2011-04-26 15:12:13

0

float是一個快速的方法,inline-block是另一種快速的方法,並具有浮動的一些優點,如不需要clear:both元素。

這裏有兩種方法http://jsfiddle.net/dGKHp/爲例

HTML:

<div id="floatExample"> 
    <div>Float Left</div> 
    <div>Float Right</div> 
    <br /> 
</div> 

<div id="inlineBlockExample"> 
    <div>Left</div><div>Right</div> 
</div> 

CSS:

#container {width:600px;margin:0 auto;} 

#floatExample div {float:left;background-color:#f00;width:50%;} 
#floatExample br {clear:both;} 

#inlineBlockExample div {display:inline-block;width:50%;background-color:#ff0;} 

這是對inline-block來龍去脈相當不錯的寫了起來:http://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/

相關問題