水平竖直居中的方法


教你如何用css做到使一个元素在水平方向上和竖直方向上的居中

以下是可以使元素快块居中的css:

1.

1
2
3
4
5
6
7
8
{
width: 400px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;
margin: -100px 0 0 -200px;
}

2.

1
2
3
4
5
6
7
8
9
10
{
width: 400px;
height: 200px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}

3.

1
2
3
4
5
6
7
8
9
10
{
width: 400px;
height: 200px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}

4.

1
2
3
4
5
6
{
width: 50%;
background: red;
display: inline-block;
vertical-align: middle;
}

5.使用table-cell来辅助实现,实现的时候需要用三层元素从而使最里层元素居中。需要的可以直接google一下。。。
6.目前使用最开心的flex-box布局实现居中,但是也要借助父元素来子元素的居中。

1
2
3
4
5
6
7
8
9
10
.father{
display: flex;
flex-direction: row;
//其实这里使用row或者column都没有问题
align-items: center;
justify-contents: center;
}
.son{
flex: 0 1 100px;
}

对flex-box不了解的话可以回去 mdn说明文档细看。

flex-box试验场