首先,准備兩個原圖:
圖一)寬>高,寬為200px
圖二)高>寬,高為200px
需求一)原圖居中
150px*150px
250px*250px
需求二)等比例縮放,最大邊撐滿,其余留空
150px*150px
250px*250px
需求三)等比例縮放,最小邊撐滿,不留空
150px*150px
250px*250px
解決方案一)使用background
<style type="text/css"> .box { width: 任意寬; height: 任意高; background: #f0f0f0; }
/*需求一)原圖居中*/ .box .bg { width: 100%; height: 100%; background: url('xxx.jpg') center center no-repeat; } /*需求二)等比例縮放,最大邊撐滿,其余留空*/ .box .bg { width: 100%; height: 100%; background: url('xxx.jpg') center center no-repeat; background-size: contain; } /*需求三)等比例縮放,最小邊撐滿,不留空*/ .box .bg { width: 100%; height: 100%; background: url('xxx.jpg') center center no-repeat; background-size: cover; } </style> <div class="box"> <div class="bg"></div> </div>
解決方案二)使用img+寬高auto(部分場景無法滿足,不推薦)
通過設置img標簽的width或height,可以解決需求一:原圖居中。
解決需求二,只能滿足以下2種情況:1)圖片寬或高>=容器 2)已知圖片比較寬還是比較高
解決需求三,必須已知圖片比較寬還是比較高
<style type="text/css"> .box { width: 寬; height: 高; background: #f0f0f0;position: relative; overflow: hidden; } /*需求一)原圖居中*/ .box img { width: auto; height: auto; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } /*需求二)等比例縮小,最大邊撐滿,其余留空(當圖片寬或高>=容器)*/ .box img { width: auto; height: auto; max-width:100%;max-height:100%; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%);} /*需求二)等比例縮放,最大邊撐滿,其余留空(當圖片寬>高)*/ .box img { width: 100%; height: auto; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%);} /*需求二)等比例縮放,最大邊撐滿,其余留空(當圖片高>寬)*/ .box img { width: auto; height: 100%; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%);} /*需求三)等比例縮放,最小邊撐滿,不留空(當圖片寬>高)*/ .box img { width: auto; height: 100%; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%);} /*需求三)等比例縮放,最小邊撐滿,不留空(當圖片高>寬)*/ .box img { width: 100%; height: auto; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%);} </style> <div class="box"> <img src="xxx.jpg" /> </div>
解決方案三)使用img+object-fit(CSS3)
在css3中提供了一個object-fit,類似於background-size,可參見https://developer.mozilla.org/zh-CN/docs/Web/CSS/object-fit
此方法必須瀏覽器支持css3或提供兼容。
<style type="text/css">
.box { width: 寬; height: 高; background: #f0f0f0; }
/*需求一)原圖居中*/ .box img { width: 100%; height: 100%; object-position: center center; object-fit: none; } /*需求二)等比例縮放,最大邊撐滿,其余留空*/ .box img { width: 100%; height: 100%; object-position: center center; object-fit: contain;} /*需求三)等比例縮放,最小邊撐滿,不留空*/ .box img { width: 100%; height: 100%; object-position: center center; object-fit: cover;} </style> <div class="box"> <img src="xxx.jpg" /> </div>
