【问题标题】:Centering inline-block element between floats在浮动之间居中 inline-block 元素
【发布时间】:2013-05-20 13:40:42
【问题描述】:

我有一个包含左侧、中间和右侧元素的标题。为了实现这一点,我有一个浮动左 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 设置为 inline-block 以尝试允许中间内容的宽度变化。但是,这样做会产生边距:自动处理浮动元素,就像它们实际持有空间一样。如果左边比右边宽,我最终会得到一个稍微(或不那么轻微)偏离中心的中间元素。

有没有办法做我想做的事,最好不求助于脚本。如果需要的话,我宁愿只处理使中间列固定宽度的后果。

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

【问题讨论】:

    标签: html css-float css


    【解决方案1】:

    您可以使用位置代替浮动: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>
    

    【讨论】:

    • 阻止它成为可行解决方案的唯一问题是存在没有任何中间内容的情况。我会将那一小部分信息编辑到 OP 中。解决方案,这不是一个可怕的解决方案,是使用脚本设置元素的高度,但我宁愿不必。
    • 另一种解决方案是使用固定了表格布局的表格:jsfiddle.net/uuq4Z/7 但很难获得居中布局.. 实际上我真的不明白你打算做什么: D 和另外:即使中间或右侧元素不存在,这也可以工作,因为它们彼此独立定位。除了你想有不同的布局(例如,如果右边不存在,右边的中间元素?)
    【解决方案2】:

    我想你想要这样的东西:

    <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。

    【讨论】:

      猜你喜欢
      • 2014-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-17
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多