水平居中
分别在块级、行内块级(未知宽高)、图片上
.size{
width: 200px;
height: 100px;
background-color: aqua;
}
.nosize{
background-color: pink;
display: inline-block;
}
.img{
}
方法一(常用)
/* test 1 */
/* 利用margin: 0 atuo */
.size{
margin: 0 auto;
}
/* 总结:图片和块级适用,行内块级不适用(可用父元素text-align: center实现),脱标流定位不适用*/
方法二(适用性广)
/* test 2 */
/* 绝对布局 + margin/translate */
.a{
position: absolute;
left: 50%;
margin-left: -100px;
}
.b{
position: absolute;
left: 50%;
transform: translateX(-50%);
}
/* 总结:这个方法无论是块级、行内块级(未知宽高)、图片 都适用
兼容性在IE7上测试了也无压力 */
方法三
/* test 3 */
/* flex */
body{
display: flex;
justify-content: center;
}
/* 总结:IE8以下不兼容flex */
方法四
/* test 4 */
/* 绝对布局 + margin0-atuo + 上下左右0 */
.size{
position: absolute;
margin: 0 auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
/* 总结:行内块级(未知宽高)无法实现,图片和块级适用 */
方法五
/* test 5 */
/* display:table + margin0-atuo */
.size{
display: table;
margin: 0 auto;
}
.nosize{
display: table;
margin: 0 auto;
}
.img{
display: table;
margin: 0 auto;
}
/* 总结:都能实现,但需要审视table作为父元素时带来的问题 */
方法六
/* test 6 */
/* width:fit-content margin0-auto */
.size{
width: fit-content;
margin: 0 auto;
}
/* 总结:只有块级元素可以用 */
其他总结: 当图片大于父元素时的居中方法: 1.使用绝对定位进行居中 2.使用父元素text-align:center+子元素margin:0 -100% (推荐使用) ### 垂直居中
分别在块级、行内块级(未知宽高)、图片上
.size{
width: 200px;
height: 100px;
background-color: aqua;
}
.nosize{
background-color: pink;
display: inline-block;
}
.img{
}
方法一
/* test 1 */
/* 绝对定位 + 上下左右 +margin-atuo0*/
.size{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto 0;
}
/* 总结: 有同理的水平居中方法 ,行内块级元素不适用*/
方法二
/* test2 */
/* 绝对定位 + top + margin 或 transform */
.a{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.b{
position: absolute;
top: 50%;
margin-top: -100px;
}
/* 总结:有同理的水平居中方法,全部适用 */
方法三
/* test3 */
/* 向外套两层div 第一层设置table 第二层设置table-cell vertical-align: middle*/
.table{
display: table;
}
.cell{
width: 500px;
height: 500px;
display: table-cell;
vertical-align: middle;
background-color: pink;
}
/* 总结:这样全部都适用,但增加了很多标签,而且还需要考虑table带来的其他问题*/
方法四
文本类用line-height属性=容器高度实现垂直居中
方法五
在悉知父子盒子的高度数据后,最方便的还是使用padding来居中
作者:AlanNgaiJX 链接:juejin.cn/post/1 来源:掘金 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。