如何將img垂直居中?


方法一:

這種方法可實現圖片超出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: 圖片居中


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM