一、水平居中
- 行内元素
1.1 父元素设置 text-align: center
.parent{
text-align:center;
}
- 块内元素
2.1 父元素设置 text-align: center,子元素设置 display: inline-block;
2.2 子元素定宽,设置 margin:auto;
2.3 子元素不定宽,设置为块级表格来显示,再将其设置水平居中,但是宽度为内容宽;
2.4 子元素使用absolute+transform,先将父元素设置为相对定位,再将子元素设置为绝对定位,向右移动子元素,移动距离为父容器的一半,最后通过向左移动子元素的一半宽度以达到水平居中,不过transform属于css3内容,兼容性存在一定问题,高版本浏览器需要添加一些前缀;
2.5 父元素使用flex+justify-content;
2.6 使用flex+margin
// 2.1
.parent{
text-align:center;
}
.children {
display: inline-block;
}
// 2.2
.children {
width: 100px;
margin:auto;
}
//2.3
.child {
display: table;
margin: 0 auto;
}
//2.4
.parent {
position:relative;
}
.child {
position:absolute;
left:50%;
transform:translateX(-50%);
}
//2.5
.parent {
display: flex;
justify-content: center;
}
//2.6
.parent {
display: flex;
}
.child {
margin:0 auto;
}
- 多块级元素
3.1 父元素用 flex布局
3.2 子元素转为行内元素,设为 display: inline-block;
//3.1
.parent {
display: flex;
justify-content: center;
}
//3.2
.parent {
text-align: center;
}
.children {
display: inline-block;
}
- 浮动元素
4.1 子元素定宽,设置relative + 负margin
4.2 flex布局
//4.1
.children {
width: 100px;
height: 100px;
float: left;
position: relative;
left: 50%;
margin-left: -50px;
}
//4.2
.parent {
display: flex;
justify-content: center;
}
.children {
float: left;
}
- 绝对定位元素
5.1 子元素绝对定位,设置 margin:auto;
.parent{
position:relative;
}
.child{
position: absolute; /*绝对定位*/
width: 100px;
height:100px;
margin: auto; /*水平居中*/
left: 0; /*此处不能省略,且为0*/
right: 0;/*此处不能省略,且为0*/
}
二、垂直居中
- 内联元素
1.1 父元素元素设置 line-height
.children {
border:1px solid black;
width: 100px;
height: 100px;
line-height: 100px;
}
- 块级元素
2.1 子元素定高,使用absolute+负margin
2.2 子元素不定高,使用absolute+transform,存在兼容性问题
2.3 通用,使用flex+align-items
2.4 父元素使用table-cell+vertical-align
//2.1
.parent {
position: relative;
}
.children {
border:1px solid black;
width: 100px;
height: 100px;
position: absolute;
top: 50%;
margin-top: -50px;
}
//2.2
.parent {
position: relative;
}
.children {
border:1px solid black;
width: 100px;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
//2.3
.parent {
display: flex;
align-items: center;
}
//2.4
.parent {
display: table-cell;
vertical-align: middle;
}
三、水平垂直居中
- 子元素定高定宽,用绝对定位与负边距实现
- 子元素不定宽高,用绝对定位与margin:auto,存在兼容性问题
- 子元素不定宽高,用绝对定位与transform,存在兼容性问题
- 父元素 flex布局
- 父元素 flex/grid 布局,子元素 margin:auto
// 1
.parent {
position: relative;
}
.children {
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
}
//2
.parent {
position: relative;
height: 200px;(必须有高度
}
.children {
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin:auto;
}
// 3
.parent {
position: relative;
}
.children {
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
// 4
.parent {
height: 200px;(必须有高度
display: flex;
justify-content: center;
align-items: center;
}
// 5
.parent {
height: 200px;(必须有高度
display: flex;
/*display: grid;*/
}
.children {
margin: auto;
}