我想在另一个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到中间。但是垂直排列呢?


当前回答

我知道这个问题是一年前提出的…… 无论如何,感谢CSS3,你可以很容易地垂直对齐div在div(例子有http://jsfiddle.net/mcSfe/98/)

<div style="width: 100px; height: 100px">
<div>
Go to Hell!
</div>
</div>

div
{
display:-moz-box;
-moz-box-align:center;
} 

其他回答

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

CSS:

#outerDiv{
    height:100%;
}

Javascript:

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

当你的高度没有设置(自动);你可以给内部div一些填充(顶部和底部),使它垂直居中:

<div>
    <div style="padding-top:20px;padding-bottom:20px">
    <!--content-->
    </div>
</div>

我想展示另一种跨浏览器的方法,可以使用CSS3 calc()解决这个问题。

我们可以使用calc()函数来控制子div的margin-top属性,当它的位置绝对相对于父div时。

使用calc()的主要优点是父元素的高度可以随时改变,并且子div将始终对齐到中间。

边缘顶部计算是动态的(通过css而不是通过脚本,这是一个非常大的优势)。

看看这个现场演示

<!DOCTYPE html>
<html>
  <head>
    <style>
      #parent{
        background-color:blue;
        width: 500px;
        height: 500px;
        position:relative;
      }
      #child{
        background-color:red;
        width: 284px;
        height: 250px;
        position:absolute;
        /* the middle of the parent(50%) minus half of the child (125px) will always             
           center vertically the child inside the parent */
        margin-top: -moz-calc(50% - 125px);
        /* WebKit */
        margin-top: -webkit-calc(50% - 125px);
        /* Opera */
        margin-top: -o-calc(50% - 125px);
        /* Standard */
        margin-top: calc(50% - 125px);
      }
    </style>
  </head>
  <body>
    <div id="parent">
      <div id="child">
      </div>
    </div>
  </body>
</html>

输出:

这将工作的方式回到IE6!

<!DOCTYPE html>在IE6上也是必需的! [将强制IE6默认严格模式以及]。

(当然,方框着色仅供演示使用)

#outer{ width: 180px; height: 180px; margin: auto; text-align: center; } #inner{ text-align: center; vertical-align: middle; width: 100px; height: 100px; display: inline-block; padding: .3em; } #center{ height: 100%; width:0px; vertical-align: middle; display: inline-block; } div {background: rgba(0,110,255,.7)} <DIV id=outer> <div id=center> </div><!--Don't break this line!--><div id=inner> The inner DIV </div> </DIV>

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