最近看了很多大神的各种关于水平居中和垂直居中的方法。我觉得用自己的话来写一遍可能记忆比较深一点。我记下几个我觉得比较常用的方法。
水平居中
行内元素,给其父元素设置text-align:center,就可以实现行内元素水平居中
.box {text-align: center;} 我要居中啦 我也居中啦
.box1 {width: 200px;height: 100px;background: #f0f0f0;margin: 0 auto;text-align: center;line-height: 100px;} p{width: 200px;height: 100px;background: #989898;margin: 0 auto;text-align: center;line-height: 100px;} 我是div 我是p标签
垂直居中
div{width: 300px;height: 50px;} p{line-height: 50px;} 我是垂直居中
.box{width: 500px;height:300px;display: table-cell;background: #f0f0f0;vertical-align: middle;} 我是垂直居中 我是测试文字啦啦啦我是测试文字啦啦啦 我是垂直居中 我是测试文字啦啦啦我是测试文字啦啦啦 我是垂直居中 我是测试文字啦啦啦我是测试文字啦啦啦我是测试文字啦啦啦 我是垂直居中 我是测试文字啦啦啦我是测试文字啦啦啦
水平垂直居中
.box{width: 200px;height:300px;background: #f0f0f0;position: absolute;top:50%;margin-top: -150px;left: 50%;margin-left: -100px;} cdfdsfsf
.box{display: flex;height: 300px;background: #ccc;} .box-child{width: 100px;height: 100px;margin: auto;background: #ddd;} sdfs
.box{position: absolute;top:50%;left:50%;transform: translate(-50%,-50%);-webkit-transform: translate(-50%,-50%);-moz-transform: translate(-50%,-50%);-o-transform: translate(-50%,-50%);background: #ccc;} 因为不知道宽高度,所以主要用translate属性拉回未知元素XY轴上的位置实现居中 若是单纯实现未知高度的元素居中,只要用到transform:translateY(-50%)即可实现
.box{display: flex;justify-content: center;align-items: center;height: 300px;background: #ccc;} .box-child{width:200px;height: 100px;border:1px solid #ddd;} 定义居中元素的父元素justify-content和align-items属性为center即可, 需要设置足够的高度,不然只有水平居中效果



