Home >Web Front-end >CSS Tutorial >Three methods of horizontally and vertically centering absolutely positioned elements
This time I will bring you three methods of absolute positioning horizontal and vertical centering of elements. What are the precautions to achieve horizontal and vertical centering of absolutely positioned elements? The following is a practical case. , let’s take a look.
1.css to achieve centering
Disadvantages: You need to know the width and height of the element in advance.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box{ width: 600px; height: 400px; position: absolute; left: 50%; top: 50%; border:1px solid #000; background:red; margin-top: -200px; /* 高度的一半 */ margin-left: -300px; /* 宽度的一半 */ } </style> </head> <body> <p class="box"> </p> </body> </html>
2. CSS3 achieves horizontal and vertical centering
Note: No matter what the size of the element, it can be centered. However, this writing method is only compatible with IE8 and above, and can be ignored on mobile terminals.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box{ width: 600px; height: 400px; position: absolute; left: 50%; top: 50%; border:1px solid #000; background:red; transform: translate(-50%, -50%); /* 50%为自身尺寸的一半 */ } </style> </head> <body> <p class="box"> </p> </body> </html>
3. Margin: auto to achieve centering
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box{ width: 600px; height: 400px; position: absolute; left: 0; top: 0; right: 0; bottom: 0; border:1px solid #000; background:red; margin: auto; /* 有了这个就自动居中了 */ } </style> </head> <body> <p class="box"> </p> </body> </html>
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other php Chinese websites related articles!
Recommended reading:
Detailed explanation of dynamic loading of css
Detailed explanation of the process of implementing fan-shaped animation menu in CSS3
How to use the webkit-tap-highlight-color property of CSS3
The above is the detailed content of Three methods of horizontally and vertically centering absolutely positioned elements. For more information, please follow other related articles on the PHP Chinese website!