2011-04-26 68 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/

相关问题