CSS Flex圖片固定區塊高度寬度垂直左右置中

12 月 22, 2018 | CSS, | 0 條留言

利用CSS Flex將圖片高寬度max100%對應外部區塊,上下垂直左右置中顯示於區塊中,這樣一來不管圖片大小多大,圖片都能正常比例完整顯示於區塊中。

注意:Flex只支援較新的瀏覽器。

HTML

<div class="box"> 
     <img class="imgcenter" src="http://p3.pstatp.com/origin/2ee200021b01de8df129"></img> 
</div>

CSS

.box{ 
      width: 800px; 
      height: 600px; 
      border: 1px solid #f00; 
      margin: auto; 
      display: flex; 
      justify-content: center; 
      align-items: center; 
} 
.imgcenter{ 
     max-width:100%; 
     max-height:100%; 
} 

DEMO

See the Pen Flex + image align by Leon Cheng (@jq153387) on CodePen.