Home > Article > Web Front-end > How to center a div in html
The methods to center a div in HTML include: the margin method sets the left margin and top margin of the margin to the value of the parent element minus the child element and then divides it by 2 to center the div; in addition, the position method can also center the div Centering
When laying out the page, we often center the main part of the web page on the page. This requires us to achieve horizontal centering of the div. Next, we will introduce how to center the div on the page in detail in the article. It has certain reference value and I hope it will be helpful to everyone
[Recommended course: HTML Tutorial]
margin method
You can use margin to center the div. The value set for margin-left is the width of the parent element minus the width of the child element and then divided by 2. (In this example: (400-100)/2=150px), the value of margin-top is the height of the parent element minus the height of the child element divided by 2 (in this example: (300-100)/2= 100px)
Example:
<style> .box{ width:400px; height: 300px; border: 1px solid #ccc; } .box1{ width:100px; height: 100px; background-color: pink; margin-left: 150px; margin-top:100px; } </style> </head> <body> <div> <div></div> </div> </body> </html>
Rendering:
##position method
You can use positioning to center the div vertically. We can set the absolute positioning of the sub-element, and set the top and left values to 50%. However, it should be noted that when using positioning, you must also set the margin value, where margin-left and The values of margin-right are all negative, and the size of the value is half the width and height of the child element<style> .box{ width:400px; height: 300px; border: 1px solid #ccc; position: relative; } .box1{ width:100px; height: 100px; background-color: pink; position: absolute; top: 50%; left: 50%; margin:-50px 0 0 -50px } </style> </head> <body> <div class="box"> <div class="box1"></div> </div> </body> </html>
Rendering:
Reference for this article: https://www.html.cn/doc/html/layout/
HTML tag index: https://www.html.cn/sitemap.html
Summary: The above is the entire content of this article. I hope this article can help everyone learn How to center a div on the pageThe above is the detailed content of How to center a div in html. For more information, please follow other related articles on the PHP Chinese website!