开发者

prevent floating divs from wrapping

开发者 https://www.devze.com 2023-01-20 14:13 出处:网络
<style> .header { float:left; width:50%; border:1px solid black; } </style> <div style=\"width:100%;\">
<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?


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.


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.


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>


This could work:

because you don't need to float the second div it should fill up any space that is left after the first div. This allows you to add a border and still have them flush side-by-side

0

精彩评论

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

关注公众号