CSS实现垂直水平的四种居中方式

如何用CSS实现垂直水平居中,这几乎是每家公司必问的题目
今天我就来写一写四种用CSS实现垂直水平居中的方式

假设HTML中body的代码如下:

公用的CSS如下:

*{
   margin:0;
   padding:0;
 }
.size{
        width: 200px;
        height: 200px;
        background: #ccc;
 }

那么CSS四种实现垂直水平的写法如下:

1.负外边距居中

.box{
       position: absolute;
       top: 50%;
       left: 50%;
       margin-top: -100px;
       margin-left: -100px;
}

2.绝对定位居中

.box{
       position: absolute;
       top: 0;
       left: 0;
       right: 0;
       bottom: 0;
       margin: auto;
 }

3.transform居中

.box{
       position: absolute;
       top: 50%;
       left: 50%;
       transform: translate(-50%, -50%);
 }

4.flex居中

html, body{
             height:100%;
             display:flex;
             justify-content: center;
             align-items: center;
 }
.box{
       width:200px;
       height:200px;
       background:#ccc;
 }

你可能感兴趣的:(CSS实现垂直水平的四种居中方式)