一.水平居中:
(1)行内元素
把行内元素嵌套在一个块级(display:block)的父元素中,给父元素添加属性。
.parent {
text-align:center;
}
(2)块状元素
.item {
/* 有顶端外边距 */
margin: 10px auto; /*10px可变任意数值*/
}
(3)多个块状元素
将要居中元素的display设为inline-block,把父元素的text-align属性设置为center。
.parent {
text-align:center;
}
(4)多个块状元素 (flexbox布局)
把要居中的块状元素的父元素添加如下属性。
.parent {
display:flex;
justify-content:center;
}
二.垂直居中
(1)单行的行内元素
将需居中的元素的height和line-height数值设为和父元素一样的高度实现垂直居中 。
(2)多行的行内元素
使用如下属性来定义需居中元素的父元素属性。
.parent {
display: table-cell;
vertical-align:middle;
}
(3)已知高度的块状元素
.item{
top: 50%;
margin-top:-n px; /* margin-top的n值为自身高度的一半 */
position: absolute;
padding:0;
}
三.水平垂直居中
(1)已知高度和宽度的元素
<1>
.item{
position: absolute;
margin:auto;
left:0;
top:0;
right:0;
bottom:0;
}
<2>
.item{
position: absolute;
top: 50%;
left: 50%;
margin-top: -n px;
margin-left: -m px; /* 设margin-left / margin-top的n和m值为自身高度的一半 */
}
(2)未知高度和宽度元素
.item{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* css3可用 */
}
(3)flex布局
.parent{
display: flex;
justify-content:center;/*水平居中*/
align-items: center;/*垂直居中*/
}