首页 > 开发 > CSS > 正文

css实现div水平、垂直居中兼容chrome、ie8

2024-07-11 08:31:13
字体:
来源:转载
供稿:网友
示例1 chrome33、ie8测试通过:

复制代码
代码如下:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
/* 固定宽高div,在浏览器中保持水平、垂直居中 */
#div1 {
width:400px; height:300px;
position:absolute;
left:50%; top:50%;
margin-left:-200px; margin-top:-150px;
background:#f90;
}
</style>
</head>
<body>
<div id="div1"></div>
</body>
</html>

示例2 chrome33、ie8测试通过:

复制代码
代码如下:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
/* 固定宽高div在固定宽高div中保持水平、垂直居中 */
#div1 {
width: 400px;height: 200px;
background-color: #f00;
position: relative;
/* 为div赋予单元格属性,使其可以应用align属性 */
display: table-cell;
vertical-align: middle;
}
#div2 {
width: 200px;height: 100px;
background-color: #0f0;
/* 使当前标签在父标签中水平居中,即0 auto 0 auto */
margin: 0 auto;
display: block;
}
</style>
<body>
<div id="div1">
<div id="div2"></div>
</div>
</body>
</html>

示例3 chrome33、ie8测试通过:

复制代码
代码如下:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#div1 {
width: 400px;height: 200px;
background-color: #f00;
/* 使当前标签在父标签位置固定 */
position: absolute;
top: 50%;left: 50%;
margin: -100px 0 0 -200px;
}
#div2 {
width: 200px;height: 100px;
background-color: #0f0;
display: block;
/* 使当前标签在父标签中保持水平、垂直居中 */
top: 50%;left: 50%;
margin: 50px 0 0 100px;
}
</style>
</head>
<body>
<div id="div1">
<div id="div2"></div>
</div>
</body>
</html>
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表