未知图片宽高时
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8" /> 5 <title>Document</title> 6 <style> 7 .pics-container { 8 height: 100px; 9 width: 100px; 10 overflow: hidden; 11 text-align: center; 12 margin: 0 auto; 13 } 14 .pics-container img { 15 height: 100px; 16 min-width: 100%; 17 max-width: none; 18 margin: 0 -100%; 19 } 20 </style> 21 </head> 22 <body> 23 <div class="pics-container"> 24 <!-- 这里有个问题,如果图片是等高宽的话,会等比缩小,看不出hidden的效果 --> 25 <img src="3.png"> 26 </div> 27 </body> 28 </html>
note:这种居中只是相对于水平居中。
已知图片的宽度 ( 400*400)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8" /> 5 <title>Document</title> 6 <style> 7 .pics-container{ 8 width: 200px; 9 margin: 0 auto; 10 overflow:hidden; 11 position: relative; 12 height: 200px; 13 } 14 .pics-container img { 15 left: 50%; 16 top: 50%; 17 margin-top: -200px; 18 margin-left: -200px; 19 position:absolute; 20 } 21 </style> 22 </head> 23 <body> 24 <div class="pics-container"><img src="3.png" alt="" /></div> 25 </body> 26 </html>
note: 这个居中包含水平和垂直居中,但前提是已知图片的宽高。
未知图片宽高
.listpic { display: table-cell; position: relative; top: -110px; left: 208px; width: 170px; height: 128px; overflow:hidden; text-align: center; vertical-align: middle; } .pic { max-width: 100%; vertical-align: middle; }
参考资料
http://stackoverflow.com/questions/10830735/center-image-in-div-with-overflow-hidden