CSS实现元素水平垂直居中的几种方式

前言

css实现元素水平垂直居中的方法有很多种,也是前端面试题中出现频率很高的一个问题,此文简述5中常用的方式,如有错误的地方请老哥积极指正。


效果图见下

Loding...Loding...

实现: 元素a在元素box中水平垂直居中,其中box的样式为

1
2
3
4
5
6
.box{
width: 300px;
height: 300px;
background-color: bisque;
position: relative;
}

  • 方法1:使用绝对定位,相应的其父元素要设置为相对定位,即position: relative。设置a元素的top, botton, left, right四个值相等[相等即可,我这里设置为0],再用margin: auto, 即可使元素水平垂直居中, 代码如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    .a{
    width: 100px;
    height: 100px;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    background-color: #408080;
    }
  • 方法2:使用绝对定位, 元素的top和left都设置为50% 然后再把元素向左上各移动元素自身宽高的一半即可, 代码如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    .a{
    width: 100px;
    height: 100px;
    background-color: #004040;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -50px;
    margin-top: -50px;
    }
  • 方法3:与方法2类似,同样使用绝对定位,元素top和left都设置为50% 不同的是这里使用transform: translate(-50%, -50%)把元素在水平和垂直方向各移动自身宽高的一半,负号表示向左上移动, 此方法在不知道子元素的宽高时可用,代码如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    .a{
    width: 100px;
    height: 100px;
    background-color: #004040;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%)
    }
  • 方法4:使用CSS3的弹性盒子实现,点我阅读CSS3弹性盒子教程需要对父元素box设置display属性为flex,同时设置 justify-content: center[使元素在水平方向居中], aline-item: center[使元素在垂直方向居中], 代码如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    .box{
    width: 300px;
    height: 300px;
    background-color: bisque;
    display: flex;
    justify-content: center;
    align-items: center
    }

    .a{
    width: 100px;
    height: 100px;
    background-color: #004040;
    }
  • 方法5:同样使用CSS弹性盒子实现,此方法实现最简单,首先对父元素做display: flex设置,对子元素a做margin: auto设置即可

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    .box{
    width: 300px;
    height: 300px;
    background-color: bisque;
    display: flex;
    }

    .a{
    width: 100px;
    height: 100px;
    background-color: #004040;
    margin: auto;
    }

总结

通过以上几种方法基本可以解决大部分场景,其实也就是两类实现,一类使用绝对定位,一类使用C3弹性盒子,其实CSS3弹性盒子很好用,推荐使用这种方法,后期会写一些弹性盒子的其他用法,谢谢您的时间。

如果觉得文章不错,请我吃根辣条吧~~