【问题标题】:How to center multiple floated divs with fixed size如何以固定大小居中多个浮动div
【发布时间】:2014-01-19 08:47:13
【问题描述】:

我希望子 div 始终在其容器中居中,即使在调整大小时也不改变其大小。

问题示例:http://jsfiddle.net/bQMj7/

HTML

<div id='foo'><div id="container" class='group'>
    <div class='childs'>one</div>
    <div class='childs'>two</div>
    <div class='childs'>three</div>
    <div class='childs'>four</div>
    <div class='childs'>five</div>
    </div>
</div>

CSS

#foo {
       text-align:center;
    }

#container {
    background-color:beige;
    display:inline-block;
}

.childs {
    width:50px;
    height:50px;
    background-color:blue;
    float:left;
    margin-right:10px;
}

.group:after {
    clear: both;
    content: "";
    display: table;
}

我使用“inline-block / text-align:center”技术将子 div 置于其主容器的中心。当您调整窗口大小时,浮动的子 div 会折叠,这就是我想要的,但是当它们折叠时,它们不再在容器中居中。

我希望这些调整大小时折叠的 div 的云始终居中。

你有什么想法吗?

编辑:感谢您的回复,这正是我要找的!然而,我担心的是:

  • 我使用 float left 而不是 inline-block 的原因是我希望这些子 div 彼此之间没有空格(它们确实有作为行元素,除非我弄乱了我的代码缩进来拥有那些许多孩子在同一行代码)

  • 我希望折叠的最后一行与其他行一样左对齐,但整体居中。

以下是上述两个问题的更新:http://jsfiddle.net/bQMj7/6/

【问题讨论】:

    标签: css html center multiline


    【解决方案1】:

    您可以使用inline-block 来表示所有这些并伪造float : center ; 不存在

    #container{
        background-color:beige;
        display:inline-block;
    
    }
    #foo{
        text-align:center;
    
    }
    
    .childs {
        width:50px;
        height:50px;
        background-color:blue;
        display:inline-block;
        margin:5px;
    }
    

    演示http://jsfiddle.net/bQMj7/1/

    【讨论】:

    • 谢谢!请检查编辑,我添加了一些我正在寻找的解释。
    【解决方案2】:

    这是你要找的东西吗:

    http://jsfiddle.net/collabcoders/bQMj7/3/

    #container{
        background-color:beige;
        display:inline-block;
    }
    #foo{
        text-align:center; 
    }
    .childs {
        width:50px;
        height:50px;
        background-color:blue;
        display:inline-block;
        margin-right:10px;
    }
    .group:after {
        clear: both;
        content: "";
        display: table;
    }
    

    编辑:如果我理解正确,您希望块之间的空间消失但仍保持中心。 inline-block 出于某种原因在右侧放置了 4px 空间,因此只需添加 margin-right: -4px; 即可修复:

    这是新的小提琴:http://jsfiddle.net/collabcoders/bQMj7/10/

    以及对 .child 类的更新

    .childs {
        width:50px;
        height:50px;
        background-color:blue;
        display:inline-block;
        margin-right: -4px;
    }
    

    【讨论】:

    • 谢谢!请检查编辑,我添加了一些我正在寻找的解释。
    猜你喜欢
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 2011-01-07
    • 1970-01-01
    • 2013-06-08
    相关资源
    最近更新 更多