CSS vertical centering method to organize_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:52:26
Original
1455 people have browsed it

Vertical centering is often used in CSS positioning, such as pop-ups on overlays.

Method with better compatibility:

<!DOCTYPE html PUBliC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><style type="text/css">#box{ width:200px; height:100px; text-align:center; position: absolute;  left: 50%; top: 50%; margin-top: -50px;    /* 高度的一半 */ margin-left: -100px;    /* 宽度的一半 */ background-color:#ffff99;}</style></head><body><div id="box">Hello World!</div></body></html>
Copy after login

This method is only applicable to blocks with known width and height, because negative margins need to be set to correct it.
If it is a block of unknown size, you can use the following method:

<!DOCTYPE html PUBliC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><style type="text/css">#box{ width:200px; height:100px; text-align:center; position: absolute;  left: 0; top: 0; right:0; bottom:0; margin:auto; background-color:#ffff99;}</style></head><body><div id="box">Hello World!</div></body></html>
Copy after login

The reason is that absolutely positioned layout depends on three factors, one is the position of the element, one is the size of the element, and one is the margin value of the element. Elements without set size and margin will adapt to the remaining space. If the position is fixed, the size will be assigned. If the size is fixed, margin will be assigned. All are adaptive.

IE7- has different rendering methods and different rendering rules. It will not allow positioning elements to adapt.

Now with CSS3, there are new tricks:

<!DOCTYPE html PUBliC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><style type="text/css">#box{ width:200px; height:100px; text-align:center; position: absolute;  left: 50%; top: 50%; transform: translate(-50%, -50%);  background-color:#ffff99;}</style></head><body><div id="box">Hello World!</div></body></html>
Copy after login

That is to use transform instead of margin. Translate offset in transform The percentage value is relative to its own size, which is similar to the first method.

Related labels:
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