寫前端的朋友都知道,如果在上傳產(chǎn)品的時(shí)候,當(dāng)產(chǎn)品尺寸不統(tǒng)一的時(shí)候,列表容易出現(xiàn)混亂,所以我們需要寫兼容一點(diǎn),不然的話就得每次上傳前先PS圖片,但是對(duì)于很多不懂網(wǎng)站的用戶來說,他們只管上傳圖片,根本不考慮尺寸。那么我們就需要用代碼的方法 來解決一下這個(gè)問題。
**步:
需要先寫一個(gè)正方形的外部BOX,
可以參考一下我們的這一篇文章: https://www.zuoan.com.cn/News3/1485.html
第二步:
需要解決不管什么圖片都是居中的問題。
在CSS中有這樣幾個(gè)屬性,大家可以了解并嘗試一下。
.fill { object-fit: fill; } .contain { object-fit: contain; } .cover { object-fit: cover; } .none { object-fit: none; } .scale-down { object-fit: scale-down; }
這是不同尺寸的圖片在這幾個(gè)屬性下的顯示效果對(duì)比,為此我們可以看到,我們可以使用:contain和scale-down兩種屬性,
fill:默認(rèn)值。內(nèi)容拉伸填滿整個(gè)content box, 不保證保持原有的比例。
contain:保持原有尺寸比例。長(zhǎng)度和高度中短的那條邊跟容器大小一致,長(zhǎng)的那條等比縮放,可能會(huì)有留白。
cover:保持原有尺寸比例。寬度和高度中長(zhǎng)的那條邊跟容器大小一致,短的那條等比縮放。可能會(huì)有部分區(qū)域不可見。
none:保持原有尺寸比例。同時(shí)保持替換內(nèi)容原始尺寸大小。
scale-down:保持原有尺寸比例,如果容器尺寸大于圖片內(nèi)容尺寸,保持圖片的原有尺寸,不會(huì)放大失真;容器尺寸小于圖片內(nèi)容尺寸,用法跟contain一樣。
然后我們通過以上兩個(gè)小技巧就可以開始寫自己的代碼了。
<div class="col-12 col-sm-6 col-lg-3 mb-4" > <a href=""> <div class="productlist"> <div class="product-img-box"></div> <div class="pro-box"> <div class="pro-box-content"> <img src="圖片" alt="For example" class="scale-down"> </div> </div> </div> <div class="pro-title-box"> <div class="title mt-3 fs-16">For example</div> <div class="price mt-2 fweight fs-16 Koulen">$67.24</div> </div> </a> </div> 以下是CSS: .productlist{background-color:blue; width:100%; position:relative; display: inline-block;} /******外部盒子*****/ .product-img-box{margin-top: 100%;}/*****實(shí)現(xiàn)正方形或者矩形*****/ .pro-box{position:absolute;left:0;right:0;top:0;bottom: 0; width: 100%; height: 100%;} /********內(nèi)容盒子*******************/ .pro-box-content{ position: relative; width: 100%; height: 100%;} /*****pro-box的position是absolute屬性,如果不加這個(gè)內(nèi)部盒子使用:relative的話,scale-down會(huì)不起作用,因?yàn)閾尾煌獠亢凶?************/ .pro-box-content img{ width: 100%; height: 100%; } /*********必須給圖片加:100%屬性*********************/
參考以上代碼,我們*終的效果如圖:非常完美
當(dāng)然我們還可以加點(diǎn)鼠標(biāo)移上去,圖片放大一點(diǎn)的動(dòng)態(tài)效果,可能會(huì)更好一點(diǎn)。
.productlist{background-color:#F0EFF5; width:100%; position:relative; display: inline-block;} .product-img-box{margin-top: 100%;} .pro-box{position:absolute;left:0;right:0;top:0;bottom: 0; width: 100%; height: 100%;} .pro-box-content{ position: relative; width: 100%; height: 100%; overflow:hidden;} .pro-box-content img{ width: 100%; height: 100%; transition: all 0.6s} .productlist:hover .pro-box-content img{transform: scale(1.2);}
有關(guān)我們服務(wù)的更多信息,請(qǐng)聯(lián)系項(xiàng)目經(jīng)理
15899750475 楊先生