css不同情况下的各种居中方法

div水平居中
1.行内元素
.parent{
text-align: center
}
2.块级元素
.son{
margin: 0 auto ;
}
3.flex布局
.parent{
display: flex;
justify-content: center
}
4.绝对定位-定宽
.son{
position: absolute;
width: 宽度
left: 50%
margin-left : -0.5 * 宽度
}
5.绝对定位-不定宽
.son {
position : absolute;
left : 50%;
transform : translate( -50%,0 )
}

  1. left/right : 0
    .son {
    position: absolute;
    width : 宽度;
    left : 0
    right: 0
    margin: 0 auto;
    }

div垂直居中
1.行内元素
.parent {
height : 高度
}
.son {
line-height : 高度
}
2.table
.parent {
display: table;
}
3.flex
.parent {
display: flex;
align-items: center;
}
4.绝对定位-定高
.son{
position:absolute
top:50%
height: 高度
margin-top: -0.5高度
}
5.绝对定位-不定高
.son{
position: absolute
top: 50%
transform: translate( 0 ,50%)
}
6.top/bottom: 0
.son{
position:absolute;
height: 高度
top:0
bottom: 0
margin : auto 0
}

相关推荐