css实现水平垂直居中(包括flex和grid)

1,410 阅读2分钟

总结一下了解到的css实现水平垂直居中的方法(包括flex和grid)。

可以在codepen上进行测试。

原始代码

<html>

<body>
  <div class="father">
    <div class="son"></div>
  </div>
</body>

</html>
.father {
  border: solid 1px;
  width: 300px;
  height: 300px;
}

.son {
  background: #e4393c;
  width: 100px;
  height: 100px;
}

具体实现

flex 方法1

给父元素加弹性盒属性,加justify-content , align-items属性即可

.father {
  display: flex;
  justify-content: center; /*水平居中*/
  align-items: center; /*垂直居中*/
}

flex 方法2

给父元素加弹性盒属性,子元素加 margin:auto

.father {
    display: flex;
}
.son {
    margin:auto;
}

定位,父相子绝,配合transform属性

父元素相对定位,子元素绝对定位,并且使用transform平移实现

.father {
    position: relative;
}
.son {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);/* 参考自己的位置向上向左各平移自身的50% */
}

定位,父相子绝,配合margin属性

父元素相对定位,子元素绝对定位,同时上下左右为0,同时加上margin:auto

.father {
    position: relative;
}
.son {
    position: absolute;
    margin: auto;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
}

父元素display: table-cell,子元素display: inline-block;

将父元素转为一个表格单元,子元素转为行内块

.father {
    display: table-cell; /*此元素会作为一个表格单元格显示(类似 <td> 和 <th>)*/
    text-align: center; /*水平居中*/
    vertical-align: middle; /*垂直居中*/
}
.son {
    display: inline-block;  /*将其转为行内块元素*/
}

纯定位方式实现

父相子绝,子元素 left , right 各50%,再使用 margin-left , margin-top , 移动子元素自身宽高的一半

.father {
    position: relative;
}
.son {
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -50px;
    margin-top: -50px;
}

grid 方法1

.father {
    display: grid;
    align-content: center;
    justify-content: center;
}

grid 方法2

父元素加display: grid;,子元素加align-self: center; justify-self: center;即可

.father {
    display: grid;
}
.son {
    align-self: center; 
    justify-self: center;
}

参考

写在最后

如果不考虑浏览器兼容问题,flex和grid都是不错的选择;如果还需要考虑浏览器对新属性的兼容,那么就可以使用纯定位方式实现。