1.水平居中
1.1行内元素
设置text-align:center
1.2块级元素
a.子元素设置 margin:0 auto
b.使用flex布局(父元素设置如下)
.parent{ display: flex; justify-content:center; }
2.垂直居中
2.1行内元素
a.设置padding-top和padding-bottom
b.设置height和line-height的值相等
c.设置table样式(父元素设置如下)
.parent{
display: table-cell;
vertical-align: middle;
}
d.使用flex布局(父元素设置如下)
.parent{ display: flex; flex-direction:column; justify-content: center; }
2.2块级元素
2.2.1已知高度
使用position+margin-top
.parent{ position:relative; } .child{ position:absolute; height:200px; top:50%; left:0; margin-top:-100px; }
2.2.2未知高度
使用position+transfrom
.parent{ position:relative; } .child{ position:absolute; height:200px; transfrom:translateY(-50%); }
2.2.3flex布局
.parent{ display: flex; flex-direction:column; justify-content: center; }
3.水平垂直同时居中
使用position+transform
.parent{ position: relative; } .child{ position: absolute; top: 50%; left: 50%; transform:translate(-50%,-50%); }
使用flex布局
.parent{ display: flex; justify-content: center; align-items:center; }