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


当前回答

这将工作的方式回到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>

其他回答

试着像这样对齐内部元素:

top: 0;
bottom: 0;
margin: auto;
display: table;

当然还有:

position: absolute;

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

这将工作的方式回到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>

另一种方法是使用转换转换

外部Div必须将其位置设置为相对或固定,内部Div必须将其位置设置为绝对,顶部和左侧为50%,并应用transform: translate(-50%, -50%)。

div.cn { 位置:相对; 宽度:200 px; 身高:200 px; 背景:灰色; text-align:中心; } div.inner { 位置:绝对的; 上图:50%; 左:50%; 宽度:100 px; 身高:100 px; -webkit-transform (-50%, -50%); 转换:翻译(-50%,-50%); 背景:红色; } < div class = " cn”> < div class = "内部" > 测验 < / div > < / div >

测试:

Opera 24.0(最低12.1) Safari 5.1.7(最少4个带-webkit-前缀) Firefox 31.0(最低3.6带-moz前缀,最低16不带前缀) Chrome 36(最少11个带-webkit前缀,最少36个不带前缀) IE 11, 10(最小9个带-ms前缀,最小10个不带前缀) 更多浏览器,我可以使用吗?

垂直对齐任何只需3行CSS

HTML

<div class="parent-of-element">

    <div class="element">
        <p>Hello</p>
    </div>

</div>

简单的

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

CSS

.parent-of-element {
   position: relative;
   height: 500px;
   /* or height: 73.61% */
   /* or height: 35vh */
   /* or height: ANY HEIGHT */
}

.element {
  position: absolute;
  top: 50%;

  -webkit-transform: translateY(-50%);
      -ms-transform: translateY(-50%);
          transform: translateY(-50%);
}

根据shouldiprefix,这是你唯一需要的前缀

您还可以使用%作为.parent-of-element的'height'属性的值,只要元素的父元素具有高度或一些扩展其垂直大小的内容。