将div中的多个div居中

时间:2015-05-05 19:08:27

标签: javascript html css

我有一个DIV,里面有多个我想要居中的div。现在所有div都与左边对齐。

CSS是:

 #statusInfo {
        background-color:#CCD8F5;
        color:black;
        clear:both;
        text-align:center;
        padding:5px; 
    }
    #statusBox {
        padding: 2px 20px; 
        background: #84B88F;
        width: 30px;
        border-radius: 50px;
    }

HTML就是:

<div id="statusInfo">
                <div style="display: table-row">
                    <div style="display: table-cell;" id="statusBox">A1</div>
                    <div style="display: table-cell;" id="statusBox">B2</div>
                    <div style="display: table-cell;" id="statusBox">C1</div>
                    <div style="display: table-cell;" id="statusBox">D1</div>
                    <div style="display: table-cell;" id="statusBox">E1</div>
                    <div style="display: table-cell;" id="statusBox">F1</div>
                    <div style="display: table-cell;" id="statusBox">G1</div>
                </div>
            </div>

3 个答案:

答案 0 :(得分:0)

摆脱所有显示:table-row和display:table-cell。然后将它与显示中心对齐:内部div上的内联块和外部的text-align:center。

#statusInfo {text-align:center;}
#statusBox {display:inline-block;}

看到这个小提琴:http://jsfiddle.net/9hy53beu/

答案 1 :(得分:0)

 #statusInfo {
            background-color:#CCD8F5;
            color:black;
            clear:both;
            text-align:center;
            padding:5px;
        }
        #statusBox {
            padding: 2px 20px;
            background: #84B88F;
            width: 30px;
            border-radius: 50px;

        }
        .inner_list{
            width: 50%;
            margin: 0 auto;
        }

<div id="statusInfo">
    <div>
        <div class="inner_list">
        <div style="display: table-cell;" id="statusBox">A1</div>
        <div style="display: table-cell;" id="statusBox">B2</div>
        <div style="display: table-cell;" id="statusBox">C1</div>
        <div style="display: table-cell;" id="statusBox">D1</div>
        <div style="display: table-cell;" id="statusBox">E1</div>
        <div style="display: table-cell;" id="statusBox">F1</div>
        <div style="display: table-cell;" id="statusBox">G1</div>
        </div>
    </div>
</div>

https://jsfiddle.net/831dd10e/

答案 2 :(得分:0)

将整个内容放在容器div中并给它text-align: center; 然后提供#statusInfo display: inline-block;

HTML:

<div id="container">
    <div id="statusInfo">
        <!-- The rest of elements -->
    </div>
</div>

CSS:

#container {text-align: center;}
#statusInfo {
    display: inline-block;
    margin: auto 0px;
    /* the rest of styles */
}

P.s。 ID应该是唯一的。所以你可能想要使用类来代替。而不是id="statusBox"使用class="statusBox"

jsfiddle DEMO

编辑:

由于您正在使用内部div的表结构,因此给“table”一些border-spacing值:

#statusInfo {
    display: inline-block;
    margin: auto 0px;
    border-spacing: 10px 0px;
    /* the rest of styles */
}

UPDATED jsfiddle