Horizontal center

1. Inline elements

text-align:center;
Copy the code

2. Block level elements

Width to determine

1) width + margin: 0 auto; Text-align :center; text-align:center; (2) the position + marginCopy the code

Width uncertainty

(1) the position + transform (2) display: flex + the justify - content: center (3) display: table + margin: 0 auto (4) the display: inline - block + text - align: centerCopy the code

Vertical center

1. Inline elements

A single line of text is vertically centered

height=line-height
Copy the code

2. Block level elements

Multiple lines of text are vertically centered

.parent {
    width: 500px;
    height: 500px;
    background: orange;
    display: table;
}
.child {
    width: 200px;
    height: 200px;
    display: table-cell;
    vertical-align: middle;
}
Copy the code

(1) display: flex + align – items: center;

display:flex;
justify-content:center;
align-items:center;
Copy the code
The bad: bad compatibility Compatibility of writing: https://www.jianshu.com/p/49cdc1a0b69bCopy the code

② Position + reverse margin *

position: absolute;
top: 50%;
left: 50%;
margin-left: div-left;
margin-top: div-top;
Copy the code
Advantages: Good compatibility Disadvantages: need to know the size in advance, margin-top: -(half the height); Margin-left: -(half width);Copy the code

(3) the position + transform

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
Copy the code
Advantages: No need to know the dimensions in advance Disadvantages: poor compatibilityCopy the code

(4) the position + margin: auto * * *

position: absolute;
left: 0;
top: 0;
right:0;
bottom: 0;
margin: auto;
Copy the code
Advantages: do not need to know the size in advance, good compatibilityCopy the code

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;    
}
Copy the code

6, padding

Height can be used in the case of fixed, need to calculate the sizeCopy the code