使用纯CSS完成未知宽高的图片水平、垂直居中效果,兼容性非常不错的代码,烈火小编测试了IE8及火狐,都可以正常使用,在Div区块内,图片是未知宽高。不论使用何种尺寸的图片,它都会居中于DIV中,虽然代码有点多,但是兼容性方面做的挺好。 演示代码: <!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" /> <title>CSS实现图片水平垂直、居中于DIV</title> <style> h1,h2,h3,h4,h5,h6,ol,ul,li,dl,dt,dd{padding:0;margin:0;} li{list-style:none;} img{border:none;} u{text-decoration:none;} em{font-style:normal;} a{color:#0064B1;text-decoration:none;outline:none;blr:expression(this.onFocus=this.blur());} a:hover{color:#ff6700;text-decoration:underline;} body{font-size:12px;color:#444;font-family:Arial,Verdana, Helvetica, sans-serif;word-break:break-all;} .clear{height:0;overflow:hidden;clear:both;} h1{font:bold 18px microsoft yahei; color:#ff6700;margin-bottom:20px;} h2{ position:absolute;top:12px;right:20px;} h2 a{ text-indent:-9999px; background:url(/images/logo.gif) no-repeat; height:55px;width:130px; display:block;} </style> <style type="text/css"> /*For Firefox Chrome*/ .demo{border:1px #ddd solid;width:308px;height:248px;overflow:hidden;text-align:center;display:table;float:left;margin:50px;position:relative;} .demo a{display:table-cell;vertical-align:middle;width:200px;height:140px;} .demo a img{border:1px #ddd solid;margin:0 auto;max-width:200px;max-height:140px;} *+html .demo a{position:absolute;top:50%;width:100%;text-align:center;height:auto;} *+html .demo a img{position:relative;top:-50%;left:-50%;} *html .demo a{position:absolute;top:51%;width:100%;text-align:center;height:auto;display:block;} *html .demo a img{position:relative;top:-50%;left:-50%;width:expression(this.width>200?"200px":"atuo");height:expression(this.height>140?"140px":"atuo");} </style> </head> <body> <h1>图片水平垂直居中</h1> <div class="demo"><a href="#"><img src="/uploads/common/images/s_p1.jpg" /></a></div> </body> </html><br /><center>如不能显示效果,请按Ctrl+F5刷新本页,更多网页代码:<a href='http://www.veryhuo.com/' target='_blank'>http://www.veryhuo.com/</a></center>提示:可修改后代码再运行! 文章导航 碎片新闻布局的效果,Css代码实现点击后弹出遮罩层,居中显示,兼容火狐浏览器