水平居中
1、给元素设置margin:0 auto
2、margin 负值法
.outer{
position: relative;
}
.inner{
position: absolute;
left: 50%;
margin-left: -75px; /* 为自身width的一半 */
width: 150px;
height: 100px;
}
3、transform
.outer{
position: relative;
}
.inner{
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}
4、table布局
.outer{
display: table;
}
.inner{
display: table-cell;
text-align: center;
}
5、flex布局
.outer{
display: flex;
justify-content: center;
}
6、inline-block
.outer{
text-align: center;
}
.inner{
display: inline-block;
}
垂直居中
1、margin:auto
.outer{
position: relative;
}
.inner{
position: absolute;
margin: auto;
top: 0;
bottom: 0;
}
2、margin 负值法
.outer{
position: relative;
}
.inner{
position: absolute;
top: 50%;
margin-top: -50px; /* 为自身height的一半 */
width: 150px;
height: 100px;
}
3、transform
.outer{
position: relative;
}
.inner{
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
4、table布局
.outer{
display: table;
}
.inner{
display: table-cell;
vertical-align: middle;
}
5、flex布局
.outer{
display: flex;
align-items: center;
}
水平垂直居中
1、margin:auto
.outer{
position: relative;
}
.inner{
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
2、margin 负值法
.outer{
position: relative;
}
.inner{
position: absolute;
top: 50%;
left: 50%;
margin-left: -75px;
margin-top: -50px;
width: 150px;
height: 100px;
}
3、transform
.outer{
position: relative;
}
.inner{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
4、table布局
.outer{
display: table;
}
.inner{
display: table-cell;
text-align: center;
vertical-align: middle;
}
5、flex布局
.outer{
display: flex;
align-items: center;
justify-content: center;
}