码迷,mamicode.com
首页 > Web开发 > 详细

CSS垂直居中方法整理

时间:2014-12-11 23:47:31      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   使用   sp   

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. transformtranslate偏移的百分比值是相对于自身大小的,和第一个方法思路类似。

 

CSS垂直居中方法整理

标签:style   blog   http   io   ar   color   os   使用   sp   

原文地址:http://www.cnblogs.com/linda586586/p/4158679.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!