示例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>
示例4 chrome33测试通过,ie8测试不通过,参考http://www.w3school.com.cn/tiy/t.asp?f=css3_box-pack:
<!DOCTYPE html> <html> <head> <style> * { margin: 0; padding: 0; box-sizing: border-box; } /* 使用box-pack样式实现div中子元素居中 */ #div1 { width:350px; height:200px; border:1px solid black; /* Firefox */ display:-moz-box; -moz-box-pack:center; -moz-box-align:center; /* Safari, Chrome, and Opera */ display:-webkit-box; -webkit-box-pack:center; -webkit-box-align:center; /* W3C */ display:box; box-pack:center; box-align:center; } #div2 { width:100px; height:50px; background-color: #ff0; border:1px solid black; } </style> </head> <body> <div id="div1"> <div id="div2"></div> </div> </body> </html>
注:对页面中所有元素应用box-sizing:border-box样式是为了将padding、margin值都计入width、height中,即为元素指定的任何内边距和边框都将在已设定的宽度和高度内进行绘制(http://www.w3school.com.cn/cssref/pr_box-sizing.asp)。在上述代码中应用该样式无意义,但是在企业级应用中应用该样式可以减少很多界面缺陷,如标签未对齐。