CSS实现水平垂直居中

 水平居中

 1、行内元素

text-align:center;

 2、块级元素

宽度确定

    ①width+margin:0 auto;

        低版本浏览器可以使用text-align:center;

    ②position+margin

宽度不确定

    ①position+transform

    ②display:flex+justify-content:center

    ③display:table+margin:0 auto

    ④display:inline-block+text-align:center

垂直居中

1、行内元素

单行文字垂直居中

height=line-height

2、块级元素

多行文字垂直居中

.parent {

    width: 500px;

    height: 500px;

    background: orange;

    display: table;

}

.child {

    width: 200px;

    height: 200px;

    display: table-cell;

    vertical-align: middle;

}

①display:flex+align-items:center;

display:flex;

justify-content:center;

align-items:center;

    缺点:兼容性不好

    兼容性写法:https://www.jianshu.com/p/49cdc1a0b69b

②position+反向margin 

position: absolute;

top: 50%;

left: 50%;

margin-left: div-left;

margin-top: div-top;

    优点:兼容性不错

    缺点:需要提前知道尺寸,margin-top: -(高度的一半); margin-left: -(宽度的一半);

③position+transform

position: absolute;

top: 50%;

left: 50%;

transform: translate(-50%,-50%);

    优点:不需要提前知道尺寸

    缺点:兼容性不好

④position+margin:auto ***

position: absolute;

left: 0;

top: 0;

right:0;

bottom: 0;

margin: auto;

    优点:不需要提前知道尺寸,兼容性好

5、display:table-cell+vertical-align: middle

.parent {

    width: 500px;

    height: 500px;

    background: orange;

    display: table-cell;

    vertical-align: middle;

}

.child {

    width: 200px;

    height: 200px;

    background: pink;

    margin: 0 auto;   

}

6、padding

    高度固定的情况下可以使用,需要计算尺寸

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容