我想在另一个div里面居中一个div。

<div id="outerDiv">
    <div id="innerDiv">
    </div>
</div>

这是我目前使用的CSS。

    #outerDiv {
        width: 500px;
        height: 500px;
        position: relative;
    }
    
    #innerDiv {
        width: 284px;
        height: 290px;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -147px;
        margin-left: -144px;
    }

如您所见,我现在使用的方法取决于#innerDiv的宽度和高度。如果宽度/高度改变,我将不得不修改margin-top和margin-left值。是否有任何通用的解决方案,我可以使用中心的#innerDiv独立于它的大小?

我发现使用margin: auto可以水平对齐#innerDiv到中间。但是垂直排列呢?


当前回答

对于innerdiv没有指定它的高度值,没有纯CSS解决方案使它垂直居中。javascript的解决方案可以得到innerdiv的offsetHeight,然后计算style.marginTop。

其他回答

这对我很有用。可以定义外部div的宽度和高度。

代码如下:

.outer { 位置:相对; text-align:中心; 宽度:100%; 身高:150 px;//允许任何高度,也在%中。 背景:灰色; } .outer > div:first-child { 位置:绝对的; 上图:50%; 左:50%; 宽度:100%; -webkit-transform (-50%, -50%); -ms-transform: -50%, -50%; 转换:翻译(-50%,-50%); 背景:红色; } < div class = "外" > < div class = "内部" > 把你的文本或div内容放在这里! < / div > < / div >

如果你在看完上面给出的精彩答案后仍然不明白。

这里有两个简单的例子,告诉你如何实现它。

使用显示:表格单元格

.wrapper { 显示:表格单元; vertical-align:中间; text-align:中心; 宽度:400 px; 身高:300 px; 边框:1px实体#555; } .container { 显示:inline-block; text-align:左; 填充:20 px; 边框:1px solid #cd0000; } < div class = "包装" > < div class = "容器" > 使用"<strong>display: table-cell</strong>"将div居中对齐 < / div > < / div >

使用flex-box(显示:flex)

.wrapper { 显示:flex; justify-content:中心; 宽度:400 px; 身高:300 px; 边框:1px实体#555; } .container { align-self:中心; 填充:20 px; 边框:1px solid #cd0000; } < div class = "包装" > < div class = "容器" > 使用"<strong>display: flex</strong>"将div居中 < / div > < / div >

注意:在使用上述实现之前,请检查display: table-cell和flex的浏览器兼容性。

另一种实现水平和垂直居中的方法是:

.Absolute-Center {
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}

(参考)

你可以用一个简单的javascript (jQuery)块来做到这一点。

CSS:

#outerDiv{
    height:100%;
}

Javascript:

<script type="text/javascript">
    $(document).ready(function () {
        $("#innerDiv").css('top', ($(window).height() - $("#content").height()) / 2);
    });
</script>

你可以在CSS中使用flex将div垂直和水平居中;

#outerDiv{
width: 500px;
    height: 500px;
    position:relative;
    border:1px solid #000;
    margin:0 auto;
    display: flex;
    -webkit-flex-direction: row;
    flex-direction: row;
    -webkit-align-items: center;
    align-items: center;
    -webkit-justify-content: center;
    justify-content: center;

    }

#innerDiv{
    width: 284px;
    height: 290px;
    border:1px solid #eee;

}

第二个是这样的;

    #outerDiv{
        width: 500px;
        height: 500px;
        position:relative;
        border:1px solid #000;
        }

        #innerDiv{
        max-width: 300px;
        height: 200px;
        background-color: blue;
        position:absolute; 
        left:0;
        right:0;
        top:0;
        bottom:0;
        margin:auto;
        border:1px solid #000;
        border-radius:4px;
    }

以及生成的HTML:

    <div id="outerDiv">
        <div id="innerDiv"></div>
    </div>