水平居中垂直居中

625 阅读2分钟

水平居中

  1. 行内元素,父元素text-align:center,即可实现水平居中。
  2. 块级元素,给该元素设置margin: 0 auto.
  3. 使用flex布局
    .parent {
        display: flex;  /*设置弹性盒子*/
        justify-content: center; /*设置对齐方式*/
    }
  1. 使用transform属性
    .child {
        position: absolute;
        left: 50%;
        transform: translate(-50%,0);
    }
  1. 使用负值的margin-left
    .child {
        position: absolute;
        width: 固定值;
        margin-left: -0.5宽度;
    }
  1. 使用left:0;right:0;margin: 0 auto;
    .child {
        position:absolute;
        width:固定;
        left:0;
        right:0;
        margin:0 auto;
    }

垂直居中

  1. 元素为单行文本,可设置 line-height 等于父元素高度
  2. 行内块状元素,使用伪类元素
    .parent::after, .child {
        display: inline-block;
        vertical-align: middle;
    }
    .parent::after {
        content:'';
        height: 100%;
    }

这种方法兼容ie7

元素高度不定

  1. 可用vertical-align属性,而vertical-align只有在父元素为td或者th时,才会生效,对于其他块状元素,默认不支持,需使用display:table;
    .parent {
        display: table;
    }
    .child {
        display: table-cell;
        vertical-align:middle;
    }
  1. display:flex
    .parent {
        display: flex;
        align-items: center; /*非主轴对齐方式*/
    }
  1. 使用定位和translate
    .child {
        position:absolute;
        top:50%;
        -webkit-transform: translate(-50%,-50%);  
        -ms-transform: translate(-50%,-50%);
        transform: translate(-50%,-50%);
    }

有兼容性风险,可能干扰其他 transform 效果, 某些情形下会出现文本或元素边界渲染模糊的现象.

元素高度固定

  1. 定位和margin-top负值
    .child {
        position:absolute;
        top:50%;
        height:固定;
        margin-top:-0.5高度;
    }

风险:父元素空间不够时, 子元素可能不可见(当浏览器窗口缩小时,滚动条不出现时).如果子元素设置了overflow:auto, 则高度不够时, 会出现滚动条.

  1. 定位和top:0;bottom:0;
    .child {
        position: absolute;
        height:固定;
        top:0;
        bottom:0;
        margin:auto 0;
    }

总结

水平居中

  • text-align: center;
  • margin: 0 auto;
  • flex
  • translate
  • 定位+负值的margin-left
  • right:0;left:0;margin 0 auto;

垂直居中

  • line-height
  • display:inline-block,vertical-align:middle;+伪类元素
  • display:table;display:table-cell;vertical-align:middle;
  • flex
  • 定位+translate
  • 定位+margin-top负值
  • 定位和top:0;bottom:0;