HTML
示例代码:
<div class="parent">
<div class="child">Demo</div>
</div>
1、水平居中
解决方案:
1)`inline-block + text-align`
.parent{
text-align:center; //对inline类型的子元素有效
}
.child{
display:inline-block;
}
2)`table + margin`
.child{
display:table;
margin:0 auto;
}
3)`absolute + transform`
.parent{
position:relative;
}
.child{
position:absolute;
left:50%;
transform:translateX(-50%)
}
4)`flex + justify-content`
.parent{
display:flex;
justify-content:center
}
//或者
.parent{
display:flex;
}
.child{
margin:0 auto;
}
2、垂直居中
解决方案:
1)table-cell + vertical-align
.parent{
display:table-cell;
vertical-align:middle;
}
2)absolute + transform
.parent{
position:relative;
}
.child{
position:absolute;
top:50%;
transform:translateY(-50%)
}
3)flex + align-item
.parent{
display:flex;
align-items:center;
}
3、居中(水平和垂直居中)
解决方案:
1)inline-block + text-align +table + vertical-align
.parent{
display:table-cell;
text-aiign:center;
vertical-ailgn:middle
}
.child{
display:inline-block
}
2)absolute + transform
.parent{
position;relative
}
.children{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%.-50%)
}
3)flex 布局
.parent{
display:flex;
justify-content:center;
align-items:center;
}