程度垂直居中分居中元素定宽高不定宽高两种状况。

不仅限本文的实现形式,本文只总结绝对罕用的形式。

如果有公共代码:

.wp {    border: 1px solid red;    width: 300px;    height: 300px;}.box {    background: green;    }//size仅定宽须要 .box.size{    width: 100px;    height: 100px;}<div class="wp">    <div class="box size">123123</div></div>

一、定宽高

absolute + 负margin
absolute + margin auto
absolute + calc

1.absolute + 负margin

.wp {    border: 1px solid red;    width: 300px;    height: 300px;}.box {    background: green;    }.box.size{    width: 100px;    height: 100px;}

2.absolute + margin auto

.wp {    position: relative;}.box {    position: absolute;;    top: 0;    left: 0;    right: 0;    bottom: 0;    margin: auto;}

3.absolute + calc

.wp {    position: relative;}.box {    position: absolute;;    top: calc(50% - 50px);    left: calc(50% - 50px);}

二、不定宽高

absolute + transform
lineheight
css-table
flex
grid

1.absolute + transform

.wp {    position: relative;}.box {    position: absolute;    top: 50%;    left: 50%;    transform: translate(-50%, -50%);}

2.lineheight

.wp {    line-height: 300px;    text-align: center;    font-size: 0px;}.box {    font-size: 16px;    display: inline-block;    vertical-align: middle;    line-height: initial;    text-align: left; /* 修改文字 */}

3.css-table

.wp {    display: table-cell;    text-align: center;    vertical-align: middle;}.box {    display: inline-block;}

4.flex

.wp {    display: flex;    justify-content: center;    align-items: center;}

5.grid

.wp {    display: grid;}.box {    align-self: center;    justify-self: center;}

总结:

PC端有兼容性要求,宽高固定,举荐absolute + 负margin
PC端有兼容要求,宽高不固定,举荐css-table
PC端无兼容性要求,举荐flex
挪动端举荐应用flex

参考:https://segmentfault.com/a/11...