Write in front:
In the following code,.parent represents the parent element and.child represents the child element.
It is easier to center the child element vertically when the parent element has no height. Such as:
.parent {
padding: 50px 0;
}
Copy the code
Click me to view the demo
It is a good habit not to write width and height. It is recommended not to write width and height as much as possible.
But sometimes you have to write width or height dead. Here are some ways to center the child vertically if the parent element height is dead.
1. flex
Key code:
.parent {
height: 400px;
display: flex;
align-items: center;
}
Copy the code
Click me to view the demo
2. absolute + translate -50%
Key code:
.parent {
height: 400px;
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
Copy the code
Click me to view the demo
3. Absolute + negative margin
Key code:
.parent {
height: 400px;
position: relative;
}
.child {
width: 300px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px; /* Half of the child width */
margin-top: -100px; /* Half of the child height */
}
Copy the code
Click me to view the demo
4. absolute + margin: auto
Key code:
.parent {
height: 400px;
position: relative;
}
.child {
width: 300px;
height: 200px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
Copy the code
Click me to view the demo
5. The table tag
Key code:
<table>
<tr>
<td>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora harum voluptates quae velit eveniet, accusamus, quas ratione placeat! Nisi perferendis facere, error sed possimus molestias et. Quas accusantium, maiores aliquid?
</td>
</tr>
</table>
Copy the code
Click me to view the demo
Div mimics table
Key code:
.parent {
height: 400px;
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
}
Copy the code
Click me to view the demo
7. Pseudo-element with 100% height + display: inline-block
Key code:
.parent {
height: 400px;
text-align: center;
}
.parent:before,
.parent:after {
content: "";
display: inline-block;
height: 100%; /* Front and back pseudo-element height 100% */
vertical-align: middle; /* The pseudo-element is vertically centered */
}
.child {
width: 300px;
display: inline-block;
vertical-align: middle; /* The child element is vertically centered at 100% height */
}
Copy the code
Click me to view the demo
Reference source: www.yuque.com/docs/share/…