水平垂直居中

水平垂直居中是前端CSS编码中很常见的需求,本文将总结几种不同的写法。

一、垂直居中

1.line-height

如果元素内容是单行文本元素,将父元素的高度和行高设为一样就能实现垂直居中效果:

如果要居中元素是行内元素或者行内块级元素,居中方法为:

1
2
3
4
5
6
7
8
9
10
11
12
.father_class {
/* $height为父元素高度 */
height: $height;
line-height: $height;
font-size: 0;
/* 子元素样式 */
...
}
.child_class {
/* 子元素样式 */
....
}

居中效果如下:

2.absolute + 负margin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.father_class {
/* $height_father为父元素高度 */
height: $height_father;
position: relative;
/* 子元素样式 */
...
}
.child_class {
/* $height_child为子元素高度 */
height: $height_child;
position: absolute;
top: 50%;
margin-top: -($height_child/2);
/* 子元素样式 */
....
}
  1. position: absolute + margin: auto
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    .father_class {
    /* $height_father为父元素高度 */
    height: $height_father;
    position: relative;
    /* 子元素样式 */
    ...
    }
    .child_class {
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
    /* 子元素样式 */
    ....
    }

居中效果如下:

4.absolute + calc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.father_class {
/* $height_father为父元素高度 */
height: $height_father;
position: relative;
/* 子元素样式 */
...
}
.child_class {
/* $height_child为父元素高度 */
height: $height_child;
position: absolute;
top: calc(50% -$height_child/2);
/* 子元素样式 */
....
}

居中效果如图:

5.absolute + transform

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.father_class {
/* $height_father为父元素高度 */
height: $height_father;
position: relative;
/* 子元素样式 */
...
}
.child_class {
/* $height_child为父元素高度 */
height: $height_child;
position: absolute;
top: 50%;
transform: translateY(-50%);
/* 子元素样式 */
....
}

居中效果如下:

6.table + vertical-align:middle

1
2
3
4
5
6
.father_class {
display:table-cell;
vertical-align:middle;
/* 子元素样式 */
...
}

居中效果如下:

7.css table

将要居中的元素包裹在完整的表结构中:

1
2
3
4
5
6
7
8
9
<table>
<tbody>
<tr>
<td class="box">
<p class="content">Hello World!!!</p>
</td>
</tr>
</tbody>
</table>

居中效果如下:

8.flex

1
2
3
4
5
6
.father_class {
display: flex;
align-items: center;
/* 子元素样式 */
...
}

居中效果如下: