目录
垂直水平居中方式
方式1:弹f性盒子(1) (推荐)
方式2:弹性盒子(2) (推荐)
方式3:弹性盒子(3)
方式4:grid布局(1) (推荐)
方式5:grid布局(2)
方式6:通过父相子绝,子元素设置绝对定位,父元素设置相对定位。 定位+margin (推荐)
方式7:绝对定位+transform属性 (推荐)
方式8:绝对定位+calc()函数 宽高要固定 (推荐)
方式8:table-cell 表格单元 只对(行内块元素有效)
方式9:单行文本居中
公共样式:
.far{width: 400px;height: 400px;background-color: skyblue;}.son{width:100px ;height: 100px;background-color: pink;}
.farCenter{/* 设置为弹性盒子 */display: flex;/* 水平居中 */justify-content: center;/* 垂直居中 */align-items:center;}
.childCenter{}

.farCenter{/* 设置为弹性盒子 */display: flex;}
.childCenter{/* margin:auto auto auto auto; */margin: auto;}
利用子元素的align-self:center , 如果父元素设置了 align-items:center;就会覆盖掉。
.farCenter{/* 设置为弹性盒子 */display: flex;}.childCenter{/* 子元素垂直居中 */align-self: center;/* 子元素水平居中 */margin: 0 auto;}
.farCenter{display: grid;}.childCenter{margin:auto;}
.farCenter{display: grid;}.childCenter{/* 水平居中 */justify-self: center;/* 垂直居中 */align-self: center;}
.farCenter{/* 所有定位都是基于父亲的 */position: relative;}.childCenter{/* 绝对定位会脱离文档流 */position:absolute;left:0;right:0;top:0;bottom:0;margin:auto;}
原理:
具体原理去到这个链接:
绝对定位元素left、right、top、bottom值与其margin和宽高的关系 - 请叫我二狗哥 - 博客园 (cnblogs.com)
.farCenter{/* 所有定位都是基于父亲的 */position: relative;}.childCenter{/* 绝对定位会脱离文档流 */position:absolute;/* 向右移动相对于父元素宽度的50% */left:50%;/* 向下移动相对于父元素高度的50%*/top:50%;/* 移动 子元素相对于自身的宽度高度往左和往上移动50%*/transform: translate(-50%,-50%);}
.farCenter {position: relative;}.childCenter {position: absolute;/* 50%是相对于父元素宽度的50%,50px是子元素本身宽度的一半 *//* 如果不减去50px的话,元素整体会偏下,不会居中 */top:calc(50% - 50px);left:calc(50% - 50px);}
所以子元素要设置为行内块模式。
.farCenter{/* 表格单元 */display: table-cell;/* 垂直居中 */vertical-align: middle;/* 水平居中 */text-align:center;}.childCenter{display: inline-block;}
.online{width: 600px; height: 100px;background-color: pink;/* 水平居中 */text-align: center;/* 垂直居中 */line-height: 100px;}
单行文本垂直居中
