方法一:
這種方法可實現圖片超出frame尺寸時,自動選擇水平、垂直居中,效果如下
<div class="frame"> <img src="foo"/> </div> .frame { height: 160px; /*can be anything*/ width: 160px; /*can be anything*/ position: relative; } img { max-height: 100%; max-width: 100%; width: auto; height: auto; position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; }
demo: 圖片居中
方法二:
原理是,使用協助元素(這里是span),作為img的相鄰元素,同為inline-block的兩元素相鄰時增加vertical-align: middle
可使兩元素垂直居中,代碼如下
<div class=frame> <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=250 /> </div> .frame { height: 25px; /* equals max image height */ width: 160px; border: 1px solid red; white-space: nowrap; text-align: center; margin: 1em 0; } .helper { display: inline-block; height: 100%; vertical-align: middle; } img { background: #3A6F9A; vertical-align: middle; max-height: 25px; max-width: 160px; }
demo: 圖片居中