如何在外部div中水平居中内部div?

时间:2013-06-19 15:38:12

标签: javascript html centering

我需要将div水平居中于另一个div

这是我的HTML代码:

<div id="outer" class="outerDiv">
    <div id="inner" class="innerDiv">
    </div>
</div>

这是css:

.outerDiv {
    width:100px;
    height:100px;
    background:red;
}

.innerDiv {
    width:50px;
    height:50px;
    background:blue; 
    // what to add here ?
}

您可以尝试:http://jsfiddle.net/nggSG/

如何将红色div内的蓝色div水平居中?

4 个答案:

答案 0 :(得分:2)

像这样:

.innerDiv {
    width:50px;
    height:50px;
    background:blue;
    margin : 0 auto;
   }

答案 1 :(得分:2)

.innerDiv {
    margin: auto;
    width:50px;
    height:50px;
    background:blue;
}

水平居中div

答案 2 :(得分:0)

以下是您需要做的事情:

.outerDiv {
    width: 100px; height: 100px;

    background-color: red;
    position: relative;
}

.innerDiv {
    width: 50px; height: 50px;
    top: 25px; left: 25px;

    background: blue;
    position: absolute;
}

如果从内部div中减去外部div的宽度和高度并除以2,您就知道需要在内部div上移动多少。此外,外部div 必须position: relative,内部div 必须position: absolute

如果您需要更加动态的中心解决方案,我一直在使用Shipp Co的Midway.js(http://shipp.co/midway)。希望这有帮助!

编辑:jsFiddle - http://jsfiddle.net/5A9sq

答案 3 :(得分:0)

这是我的HTML

<div id="outer" class="outerDiv">
    <div id="inner" class="innerDiv">
      Inner div (centered)
    </div>
</div>

简单的css

    .outerDiv{
        width:100%;
        margin:0 auto;
        text-align: center;
        background-color: red;
    }

    .innerDiv{
        width:50%;
        display: inline-block;
        background-color: yellow;
        color: black;
    }
相关问题