Prevent floating divs from packing

<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 next to each other, blending in perfectly with the parent. This happens when there are no borders on them, but when I set the border, the second div wraps and appears below. How to avoid this?

+3
source share
4 answers

The reason for this is that 50% x 2 is already 100%. The 2 px borders are 100% + 4 px wide. To undo this, use negative 1px fields on both sides.

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

You may encounter the problem of 100% of the total width in IE .

+8
source

, , div 50% + 2 ( ). (50% + 2 ) * 2 , 100- , .

-1 .header div .

+3

Add an extra div inside 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>
0
source

This might work:

because you don’t need to float the second div, it should fill in any space left after the first div. This allows you to add a border and still have them side by side.

0
source

Source: https://habr.com/ru/post/1770720/


All Articles