Home  >  Article  >  Web Front-end  >  CSS垂直居中方法整理_html/css_WEB-ITnose

CSS垂直居中方法整理_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:52:261406browse

CSS定位中常常用到垂直居中,比如覆盖层上的弹框。

兼容性比较好的方法:

<!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>

这个方法只适用于已知宽高的块,因为要设置负边距来修正。
如果是未知尺寸的块,可以使用以下方法:

<!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>

原因是,绝对定位的布局取决于三个因素,一个是元素的位置,一个是元素的尺寸,一个是元素的margin值。没有设置尺寸和 margin 的元素会自适应剩余空间,位置固定则分配尺寸,尺寸固定边会分配 margin,都是自适应的。

IE7- 的渲染方式不同,渲染规则也不一样,他不会让定位元素去自适应。

 

现在有了CSS3,就又有新招数了:

<!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>

就是使用transform代替margin. transform中translate偏移的百分比值是相对于自身大小的,和第一个方法思路类似。

 

Statement:
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