实现水平垂直居中的几种方法

水平居中

  1. 如果是行内元素,要实现水平居中只需要将父元素设置为text-align=center
  2. 如果是固定宽度的块状元素,设置该元素本身为margin: 0 auto
  3. css3的新属性font-content,自动将元素宽度缩小到内容的宽度,然后使用margin:0 auto可以轻松的实现水平居中(目前只支持chrome和FireFox)

.son{ -moz-fit-content; -webkit-fit-content; fit-content; margin:0 auto; }

   4.绝对定位以及margin-left的负值实现水平居中

    

.son {
            position: absolute;
             50px;
            left: 50%;
            margin-left: -25px;(宽度的一半)
            background-color: blue;
            text-align: center;
        }

   5.绝对定位left right同时设置为0 同时设置margin:0 auto

.son{
            position: absolute;
             50px;
            left: 0;
            right: 0;
            background-color: blue;
            margin: 0 auto;
            height: 100%;
        }

垂直居中

  1. 若元素为单行文本,直接设置其text-align为父元素的高度
  2. 利用position以及top bottom属性
.son{
    position:absolute;
    height:固定;
    top:0;
    bottom:0;
    margin:auto 0;
}

  3.利用margin的负值

.son{
    position:absolute;
    top:50%;
    height:固定;
    margin-top:-0.5高度;
}

  4.利用vertical-align

.parent::after, .son{
    display:inline-block;
    vertical-align:middle;
}
.parent::after{
    content:'';
    height:100%;
}
原文地址:https://www.cnblogs.com/yinping/p/11262620.html