在網頁設計過程當中,有時候會但願圖片垂直居中的狀況。並且,須要垂直居中的圖片的高度也不肯定,這就會給頁面的佈局帶來必定的挑戰。下面總結了一下,曾經使用過的幾種方法來使圖片垂直居中,除了第一種方法只限於標準瀏覽器外,另外兩種方法的兼容性還不錯。css
將外部容器的顯示模式設置成display:table,這個設置的意思不用多說了吧… img標籤外部再嵌套一個span標籤,並設置span的顯示模式爲display:table-cell,這樣span內部的內容就至關於表格,能夠很方便的使用vertical-align屬性來對齊其中的內容了。html
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>方法1 - 未知高度的圖片垂直居中 - www.nowamagic.net</title> <style type="text/css"> body { height:100%; } #box{ width:500px;height:400px; display:table; text-align:center; border:1px solid #d3d3d3;background:#fff; } #box span{ display:table-cell; vertical-align:middle; } #box img{ border:1px solid #ccc; } </style> <!--[if lte IE 7]> <style type="text/css">? #box{ position:relative; overflow:hidden; } #box span{ position:absolute; left:50%;top:50%; } #box img{ position:relative; left:-50%;top:-50%; } </style> <![endif]--> </head> <body> <div id="box"> <span><img src="images/demo_zl.png" alt="" /></span> </div> </body> </html>
標準瀏覽器的狀況仍是和上面同樣,不一樣的是針對IE6/IE7利用在img標籤的前面插入一對空標籤的辦法。express
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>方法2 - 未知高度的圖片垂直居中 - www.nowamagic.net</title> <style type="text/css"> body { height:100%; } #box{ width:500px;height:400px; display:table-cell; text-align:center; vertical-align:middle; border:1px solid #d3d3d3;background:#fff; } #box img{ border:1px solid #ccc; } </style> <!--[if IE]> <style type="text/css">? #box i { display:inline-block; height:100%; vertical-align:middle } #box img { vertical-align:middle } </style> <![endif]--> </head> <body> <div id="box"> <i></i><img src="images/demo_zl.png" alt="" /> </div> </body> </html>
在img標籤外包裹一個p標籤,標準瀏覽器利用p標籤的僞類屬性:before來實現居中,另外,對於IE6/IE7使用了CSS表達式來實現兼容。瀏覽器
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>方法3 - 未知高度的圖片垂直居中 - www.nowamagic.net</title> <style type="text/css"> body { height:100%; } #box{ width:500px;height:400px; text-align:center; border:1px solid #d3d3d3;background:#fff; } #box p{ width:500px;height:400px; line-height:400px; /* 行高等於高度 */ } /* 兼容標準瀏覽器 */ #box p:before{ content:"."; /* 具體的值與垂直居中無關,儘量的節省字符 */ margin-left:-5px; font-size:10px; /* 修復居中的小BUG */ visibility:hidden; /*設置成隱藏元素*/ } #box p img{ *margin-top:expression((400 - this.height )/2); /* CSS表達式用來兼容IE6/IE7 */ vertical-align:middle; border:1px solid #ccc; } </style> </head> <body> <div id="box"> <p><img src="images/demo_zl.png" alt="" /></p> </div> </body> </html>