1. Use margin
p {
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;}
Copy after login
## Analysis:
- top: 50%; left: 50%; Let the top left of the element be vertically and horizontally centered in the parent element
- margin-top: -50px; margin-left: -50px; Let The element is offset half its distance upward and to the right
2. Use translate
p {
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);}
Copy after login
Analysis:
- top: 50%; left: 50%; Let the top left of the element be vertically and horizontally centered in the parent element
- transform: translate(-50%, -50%); Move the element up and to the right by half its distance
3. All four directions are 0, use margin Positioning
p {
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right : 0;
margin: auto;}
Copy after login
Analysis:
- All four directions When it is 0, they cancel each other out, and the box will be displayed at the initial position
- margin: auto; center the box vertically and horizontally
More【CSS 】For related articles about centered display of positioning elements, please pay attention to the PHP Chinese website!