写在前面
css居中方案是一个老生常谈的问题,主要包括水平居中和垂直居中,水平居中大家用的比较多,最常用的莫过于margin:0 auto方案了,而垂直居中,很多时候会让很多新手头疼。
常用居中方案(水平)
- margin:0 auto解决方案 (水平居中)
适用于已经知道宽度,并且其父级宽度不为0的元素水平居中。
.parent { width:800px;}.child { width:20%;//也可以是固定像素 margin:0 auto;}哈哈哈哈
<!-- more -->
2.利用text-align:center使行内元素水平居中(水平居中)
哈哈哈哈div { text-align:center}
3.flex水平居中
.parent { display:flex; justify-content:center}哈哈哈哈
4.绝对定位利用负边距居中(已知宽度)
.parent { position:relative;}.child { width:500px; position: absolute;}哈哈哈哈
5.绝对定位不知宽度居中,可以利用css transform属性,也可以利用flex居中
.parent { position:relative;}.child { position: absolute; left:50%; transform:translate(-50%);}哈哈哈哈
垂直居中方案
1.不知宽高,兼容性很高的居中方案。
.parent { position:relative;}.child { margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0;}哈哈哈哈
2.利用行高进行居中,行高和高度一致
.parent { height:50px; line-height:50px;}哈哈哈哈
3.flex方案
.parent { display: flex; justify-content: center; align-items: center;}哈哈哈哈
4.transform方案
.parent { position: relative;}.child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);}哈哈哈哈
5.已知父级高度,利用margin-top进行居中,该方案过于简单,就不贴代码了
6.绝对定位,使用负边距居中.parent { position: relative;}.child { position: absolute; width:500px; height:500px; top: 50%; left: 50%; margin-top:-250px; margin-left:-250px;}哈哈哈哈
- 还有一种是利用table方案居中,我觉得这种方案可能过时了,想了解的话可以自己百度一下
写在最后
本文已经列出了大多情况下都可以解决的居中方案,还有一些比较居中,例如浮动元素居中可以参考绝对定位居中,如果不考虑兼容性的话,flex居中是最方便的方案,大家可以自由的去根据实际情况去选择需要的方案