如何将两个div放在一起

时间:2011-04-26 15:06:44

标签: html

在网页上,我有两个div。我想将第二个div恰好放在另一个div上,以便它们排成一行。

4 个答案:

答案 0 :(得分:9)

您可以使用float CSS样式。为第一个div设置为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>

答案 1 :(得分: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的最后一个兄弟。

答案 2 :(得分: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>

答案 3 :(得分:1)

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-blockhttp://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/

的细节的非常好的写作