How to achieve horizontal, vertical and centered div effects:
Sometimes we may need to center a div in its parent container. Let’s look at the code example first and then analyze it.
Code example:
<!DOCTYPE html><html><head><meta charset=" utf-8"><meta name="author" content="http://www.softwhy.com/" /><title>蚂蚁部落</title><style type="text/css">.parent{ width:500px; height:500px; border:1px solid red; position:absolute;}.children{ width:200px; height:100px; background-color:green; position:absolute; top:50%; left:50%; margin:-50px 0 0 -100px;}</style></head><body><div class="parent"> <div class="children"></div></div></body></html>
In the above code, the position attribute is used to achieve the vertical centering effect of the object. After using top:50% and left:50% on the sub-object, the centering of the object is not achieved, but the vertical centering of the upper left corner of the object is achieved, as shown below:
What we need is to center the object, so that the entire object is centered, so we use margin:-50px 0 0 -100px to move the object up and to the left by half the height and half the width respectively.
Special note:
The parent object uses absolute positioning, otherwise the absolute positioning of the child object will use the window as the reference object.
The original address is: http://www.51texiao.cn/div_cssjiaocheng/2015/0503/586.html
The most original address is: http://www.softwhy.com