多个div元素的水平对齐

时间:2014-04-07 17:03:01

标签: html css html5 css3 css-float

我在父div中有三个div。我设法将它们水平对齐,但是当我添加边框时,第三个div跳转到新行。我已经阅读了很多关于这个问题的主题,但找不到正确的答案。我相信,内部div +边界的宽度变成了适合容器的脂肪。任何帮助表示赞赏。

HTML code:

<div class="a">
    <div class="b">
        <h3>Glavna pisarna</h3><hr />
        <p><b>Tel.:</b> 03 749 20 90</p>
        <p><b>Gsm:</b> 041 651 483</p>
        <p><b>Fax:</b> 03 749 20 90</p>
        <p><b>E-mail:</b></p>
    </div>
    <div class="c">
        <h3>Direktor</h3><hr />
        <p><b>Tel.:</b> 03 749 20 90</p>
        <p><b>Gsm:</b> 041 651 483</p>
        <p><b>Fax:</b> 03 749 20 90</p>
        <p><b>E-mail:</b></p>
    </div>
    <div class="d">
        <h3>Bar</h3><hr />
        <p><b>Tel.:</b> 03 749 20 90</p>
        <p><b>Gsm:</b> 041 651 483</p>
        <p><b>Fax:</b> 03 749 20 90</p>
        <p><b>E-mail:</b></p>
    </div>
</div>

CSS代码:

.a{
    width: 100%;
    height: 220px;
    background-color: #CAE4FF;
}

.b, .c, .d{
    float: left;
    width: 33.33333333333%;
    height: 220px;
    background-color: white;
}

.b h3, .c h3, .d h3{
    margin-left: 11px;
}

.b p, .c p, .d p{
    margin-left: 11px;
}

.b hr, .c hr, .d hr{
    width: 95%;
    margin: auto;
}

.b, .c{
    border-right: solid 1px;
}

5 个答案:

答案 0 :(得分:3)

这将完成这项工作:

.b, .c, .d {
    float: left;
    width: 33.33333333333%;
    height: 220px;
    background-color: white;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;    
    box-sizing: border-box;       
}

演示 http://jsfiddle.net/jvLxh/

原因:您需要在div的{​​{1}}的总宽度中加入边框宽度

阅读更多 box-sizing: border-box;http://www.w3.org/TR/css3-ui/#box-sizing0

答案 1 :(得分:1)

我认为Arbel关于使用box-sizing的建议是最好的,或者至少是最现代的解决方案,但也可以使用额外的div。

在每个div中添加一个额外的div。外部div(a,b,c)的宽度为33.33%,新的内部div获得边框并自动占用可用的宽度。

如果您需要支持不支持border-box的IE7,这将非常有用。有关详细信息,请参阅http://caniuse.com/css3-boxsizing

答案 2 :(得分:0)

为什么不使用简单的表格并指定宽度?                                                                             

答案 3 :(得分:-1)

通过添加额外1px溢出的边框,您在“a”容器上的宽度为100%。

我建议尽量减少b,c,d容器的宽度,以适应你要添加的额外1个像素。

答案 4 :(得分:-1)

只需尝试:

width: 33.2%;

你的33.3333333%将它放到新线上的原因是因为它现在超过了100%的标记(因为你的额外的1px边界,导致它结束)