在浮动之间居中嵌入块元素

时间:2013-05-24 21:09:49

标签: html css-float css

我的标题包含左侧,中间和右侧的元素。为了达到这个目的,我有一个浮动左div,一个浮动右div和一个0自动div,例如:http://jsfiddle.net/huggz/uuq4Z/1/

<div style="text-align: center;" >

    <div style="width: 200px; height: 100px; background: red; float: left;"></div>
    <div style="width: 100px; height: 100px; background: blue; float: right;"></div>

    <div style="background: green; margin: 0 auto; display: inline-block;">
        <div style="width: 150px; height: 100px; background: orange;"></div>
    </div>

</div>

我将中间div设置为内联块,以尝试允许中间内容的宽度变化。然而,这样做,使边距:自动处理浮动元素,就像它们实际上占有空间一样。如果左边比右边宽,我最后会有一个稍微(或不那么轻微)偏心的中间元素。

有没有办法做我正在尝试做的事情,最好不要诉诸脚本。如果需要的话,我宁愿只处理使中间列固定宽度的后果。

[编辑] 我应该提一下,有些情况下不存在中间或正确的内容。

2 个答案:

答案 0 :(得分:1)

你可以使用position而不是float:http://jsfiddle.net/uuq4Z/5/

<div style="text-align: center; position: relative;" >

    <div style="width: 200px; height: 100px; background: red; position: absolute; left: 0; top: 0"></div>
    <div style="width: 100px; height: 100px; background: blue; position: absolute; right: 0; top: 0;"></div>
    <div style="background: green; display: inline-block;">
        <div style="width: 150px; height: 100px; background: orange;"></div>
    </div>

</div>

答案 1 :(得分:1)

我想你想要这样的东西:

<div>
    <div style="width: 200px; height: 100px; 
                background: red; float: left;"></div>
    <div style="width: 100px; height: 100px; 
                background: blue; float: right;"></div>

    <div style="background: green; display: block; margin: 0 100px 0 200px;">
        <div style="width: 150px; height: 100px; 
                    background: orange; margin: 0 auto;"></div>
    </div>

</div>

与小提琴:http://jsfiddle.net/audetwebdesign/AFQV3/

我会保持中心元素流入(不浮动)并设置左右 边距因此允许左右浮动元素。

然后中心div将有一块空间,您可以在其中设置其他元素, 例如,橙色div,它位于浮动之间。

相关问题