如何将两个div放在一起

AGu*_*ald 2 html

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

Mik*_*scu 9

您可以使用floatCSS样式.将其设置left为第一个div.第二个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>
Run Code Online (Sandbox Code Playgroud)

注意,有时可能需要给浮动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>
Run Code Online (Sandbox Code Playgroud)