简体   繁体   English

防止浮动div包装

[英]prevent floating divs from wrapping

<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. 我希望两个内部div在彼此旁边出现,完全适合父母。 This happens when there is no border set on them, but when I do set a border, the second div wraps and appears below. 当没有设置边框时会发生这种情况,但是当我设置边框时,第二个div会换行并显示在下面。 How do I avoid that? 我该如何避免?

The reason this happens is because 50% x 2 is already 100%. 发生这种情况的原因是因为50%x 2已经是100%。 The 2 px borders make the width 100% + 4 px. 2 px边框使宽度为100%+ 4 px。 To undo this, use negative margins of 1px on either sides. 要撤消此操作,请在任一侧使用1px的负边距。

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

You may run into the 100% combined width issue in IE . 您可能会在IE中遇到100%组合宽度问题

Essentially, what is happening is that your div's are sized 50% + 2 pixels (one for each border) wide. 基本上,正在发生的事情是你的div的大小为50%+ 2像素(每个边框一个)。 Because (50% + 2 pixels) * 2 is wider than your 100% container, it forces the floats to wrap. 因为(50%+ 2像素)* 2比100%容器宽,所以它会强制浮动包裹。

Applying a -1 pixel margin to the left and right sides of your .header div's should do the trick. 在.header div的左侧和右侧应用-1像素边距应该可以解决问题。

Add an extra div inside the divs that need a border called header-inner. 在div中添加一个额外的div,需要一个名为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. 因为你不需要浮动第二个div它应该填满第一个div之后留下的任何空间。 This allows you to add a border and still have them flush side-by-side 这允许您添加边框并仍然使它们并排齐平

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM