真实以本篇为准,有遗漏,欢迎补充
1、水平居中
1.1、行内元素的水平居中(span、文字、图片、input)
父级 {
text-align: center;
}
1.2、块级元素水平居中:分情况
>> 有宽度的块级元素
本身 {
margin: 0 auto;
}
本身 { //推荐
margin-left: auto;
margin-right: auto;
}
>> 宽度不固定的元素:
方法一:定位法
父级{position: relative;}子级{position: absolute;left: 50%;transform:translateX(-50%);}方法2: 通过给父元素设置 float,然后给父元素设置 position:relative 和 left:50%,子元素设置 position:relative 和 left: -50% 来实现水平居中。
.wrap{float:left;position:relative;left:50%;clear:both;}.wrap-center{position: relative;left:-50%;}} 方法3:flex法
父级{display: flex;flex-direction: row;//设置主轴justify-content: center;//主轴方向居中} 2、垂直居中
2.1、行内元素(span、img、文字)垂直居中:
父级 {height : 100px;line-height: 100px;} 2.2、块级元素:表格布局法
父级 {display: table-cell;vertical-align: middle;} 3、水平垂直居中:
3.1:必须有宽度:定位法:上下左右为0,margin:auto
本身 {position: absolute;top: 0;left: 0;bottom: 0;right: 0;margin: auto;width: 200px;height: 200px;background: red;}3.2 有宽度的块级元素:定位+回移50%法
.center {position: absolute;top: 50%;left: 50%;margin-top: -100px;margin-left: -100px;width: 200px;height: 200px;background: red;}
3.3 flex法:让元素在父级框里是水平垂直居中的
.fa{display:flex;flex-direction: row;//确定主轴align-items: center;//交叉轴居中justify-content: center;//主轴居中border: 1px solid greenyellow;} 3.4 grid方式
.parent {
height: 140px;
display: grid;
}
.child {
margin: auto;
}