开发者

Is it possible to put two div elements side-by-side without using CSS float?

开发者 https://www.devze.com 2023-04-05 22:58 出处:网络
I keep finding that IE and Firef开发者_开发技巧ox do strange things to surprise me when I use CSS float to put two elements side-by-side on a page.

I keep finding that IE and Firef开发者_开发技巧ox do strange things to surprise me when I use CSS float to put two elements side-by-side on a page.

Is it possible to have two divs side by side on a web page without using CSS float?

<div id='div1'>
<p> div1 p1 </p>
<p> div1 p2 </p>
</div>
<div id='div2'>
<p> div2 p1 </p>
<p> div2 p2 </p>
</div>


You could do it with absolute positioning.

<div id="container">
<div id='div1'>
<p> div1 p1 </p>
<p> div1 p2 </p>
</div>
<div id='div2'>
<p> div2 p1 </p>
<p> div2 p2 </p>
</div>

And sample CSS.

#container {
position: relative;
width: 800px;
}
#div1, #div2 {
position: absolute;
width: 400px;
}
#div1 {
left: 0;
}
#div2 {
left: 400px;
}


DIVs are block elements. You can make them inline be using display:inline or display:inline-block or you can use absolute positioning


Except for float, you can also give them: display: inline-block or display: inline, but that will probably give you other problems.

But remember, 'never leave a floated element uncleared!' If you remember that, your troubles will be few.


Rather than float, you can set their display to display: inline;, which will make them inline elements rather than block-level ones.


Try,

<div style="display:table">
  <div style="display:table-row">
    <div style="display:table-cell">
       <p> div1 p1 </p>
       <p> div1 p2 </p>

    </div>
    <div style="display:table-cell">
       <p> div1 p1 </p>
       <p> div1 p2 </p>
     </div>
  </div>
</div>

Note: This is not working in lower version ie.


If you are having troubles with borders and widths do this: make outer most div a wrapper (width/height only) then style accordingly on the inside. Only add padding to the elements on the inside.

Remember that border always takes away from your width. So if you have a 200px wide box and you want 2px border then your width is 196px.

<div class="wrapper" style="height:200px">...do stuff here</div>

0

精彩评论

暂无评论...
验证码 换一张
取 消