tags:

views:

54

answers:

4
<style>
.header {
    float:left;
    width:50%;
    border:1px solid black;
}
</style>

<div style="width:100%;">
    <div class="header">Hello</div>
    <div class="header">World</div> 
</div>

I want the two inner divs to appear beside each other fitting perfectly inside the parent. This happens when there is no border set on them, but when I do set a border, the second div wraps and appears below. How do I avoid that?

+9  A: 

The reason this happens is because 50% x 2 is already 100%. The 2 px borders make the width 100% + 4 px. To undo this, use negative margins of 1px on either sides.

Demo: http://jsfiddle.net/rfSMX/1/

You may run into the 100% combined width issue in IE.

meder
+1 that is quick and correct :)
Sarfraz
and jsfiddle is cool.
manu1001
+3  A: 

Essentially, what is happening is that your div's are sized 50% + 2 pixels (one for each border) wide. Because (50% + 2 pixels) * 2 is wider than your 100% container, it forces the floats to wrap.

Applying a -1 pixel margin to the left and right sides of your .header div's should do the trick.

Matthew Vines
A: 

Add an extra div inside the divs that need a border called header-inner.

<style>
.header {
    float:left;
    width:50%;
}
.header-inner {
    padding: 10px;
    border: 1px solid #ccc;
}
</style>

<div style="width:100%;">

    <div class="header"><div class="header-inner">
        Hello
    </div></div>

    <div class="header"><div class="header-inner">
        World
    </div></div>

</div>
woodscreative
A: 
Alex