头闻号

历城区华轩化工产品经营部

其他造纸化学品|其他皮革化学品|医药中间体|其他农药原药|食品添加剂|其他化学试剂

首页 > 新闻中心 > 科技常识:css实现div水平、垂直居中兼容chrome、ie8
科技常识:css实现div水平、垂直居中兼容chrome、ie8
发布时间:2023-02-01 09:56:53        浏览次数:5        返回列表

今天小编跟大家讲解下有关css实现div水平、垂直居中兼容chrome、ie8 ,相信小伙伴们对这个话题应该有所关注吧,小编也收集到了有关css实现div水平、垂直居中兼容chrome、ie8 的相关资料,希望小伙伴们看了有所帮助。

示例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"> #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"> #div1 { width: 400px;height: 200px; background-color: #f00; position: relative; display: table-cell; vertical-align: middle; } #div2 { width: 200px;height: 100px; background-color: #0f0; 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; } #div1 { width:350px; height:200px; border:1px solid black; display:-moz-box; -moz-box-pack:center; -moz-box-align:center; display:-webkit-box; -webkit-box-pack:center; -webkit-box-align:center; 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)。在上述代码中应用该样式无意义 但是在企业级应用中应用该样式可以减少很多界面缺陷 如标签未对齐。

来源:爱蒂网