1. Use margin
p {
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;}
## 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%);}
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;}
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!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn