Horizontal and vertical center separated elementsFixed width highwithIndefinite wide highTwo cases.

Not limited to the implementation methods in this article, only the relatively common ones are summarized in this article.

If there is a public code:

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

First, fixed width and height

Absolute + negative margin


absolute + margin auto


absolute + calc

1. The absolute + negative 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);
}

Two, variable width and height

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; /* Correct text */}

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;
}

Conclusion:

PC has compatibility requirements, width and height fixed, recommended absolute + negative margin


PC has compatibility requirements, width and height is not fixed, recommended CSS-Table


There is no PC compatibility requirement. Flex is recommended


Flex is recommended for mobile

Reference:https://segmentfault.com/a/11…