这是前端布局经常用到的布局方式,水平垂直居中;面试也经常会问到。
一. 绝对定位实现居中
注意:使用绝对定位布局的时候,外层元素必须也设置有position属性,具体设置为什么值看具体情况。只要不是static就行。
1.通过定位+margin实现
将四个方向的偏移量设为0,然后用margin:auto实现居中。
1 .center {
2 /* div的基本属性 */
3 height: 500px;
4 width: 500px;
5 background-color: blue;
6 /* 绝对定位 */
7 position: absolute;
8 /* 通过定位+margin实现双居中 */
9 top: 0;
10 left: 0;
11 bottom: 0;
12 right: 0;
13 margin:auto;
14 }
2.通过定位+transform实现
设置top和left偏移量为50%,此时的正中间是div开始的位置,也就是div的坐上角,所以还需要向左上方向移动50%的宽(高)度。
.center {
/* div的基本属性 */
height: 500px;
width: 500px;
background-color: blue;
/* 绝对定位 */
position: absolute;
/* 通过定位+transform实现双居中 */
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
3.通过定位+margin实现(这种方法必须要知道居中div的长宽)
这个方法类似于第二种,通过设置top、left的偏移量,然后通过把margin-top,margin-left的值设置为50%的宽(高)度作为矫正。
1 .center {
2 /* div的基本属性 */
3 height: 500px;
4 width: 500px;
5 background-color: blue;
6 /* 绝对定位 */
7 position: absolute;
8 /* 通过定位+margin实现双居中 */
9 top: 50%;
10 left: 50%;
11 margin-top: -250px;
12 margin-left: -250px;
13 }
二. 通过flex布局实现居中
1.通过把父元素变成flex布局,再设置align-items和justify-content属性即可
1 .father{
2 /* 父元素的基本属性 */
3 height: 1000px;
4 width: 1000px;
5 border: 1px solid red;
6 /* 设置为flex布局 */
7 display: flex;
8 /* 设置flex属性 */
9 align-items: center;
10 justify-content: center;
11 }
12 .center {
13 /* div的基本属性 */
14 height: 500px;
15 width: 500px;
16 background-color: blue;
17 }