未知宽高的Div垂直水平居中的几种方法

125 阅读1分钟

下面公共的html和css如下:

 <div id="parent">
      <div id="child"></div>
  </div>
  <style>
        #parent{
            background-color: red;
            width:300px;
            height:300px;
        }
        #child{
            background-color: blue;
            width: 100px;
            height:100px;
        }
    </style>
  

flex

将父元素的定位flex布局,justify-content是为了使flex布局里面的元素水平居中,align-items是使flex布局中的子元素垂直居中。

#parent{
     display: flex;
     justify-content: center;
     align-items: center;
}

css3的transform

子元素absoluted定位,父元素为relative是为了使子元素相对于父元素进行定位,left:50%是子元素向右移动父元素的50%,top同理,transform的第一个-50%是子元素向左移动自身长度的50%,

#parent{
    position:relative;
}
#child{
    position:absolute;
    left:50%;
    top:50%;
    transform: translate(-50%,-50%);
}

display:table-cell

注意:当使用table-cell布局时,子元素一定要设置为inline-block

#parent{
    display:table-cell;
    text-align:center;
    vertical-align:middle;
}
#child{
    display:inline-block;
}

margin: 0 auto;

这个比较常用的属性,能够使元素水平居中

效果:

代码如下:

#child{
    margin:0 auto;
}