Home > Web Front-end > HTML Tutorial > How to achieve horizontal and vertical centering effect of div_html/css_WEB-ITnose

How to achieve horizontal and vertical centering effect of div_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:41:01
Original
1185 people have browsed it

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>
Copy after login

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template