水平垂直居中分居中元素定宽高不定宽高两种情况。

不仅限本文的实现方式,本文只总结相对常用的方式。

假如有公共代码:

.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...


超帅的轻省回望
15 声望0 粉丝