[英]How to set all images to equal width and height without stretching
如何在不拉伸的情況下將所有圖像設置為 40x40 的相同大小?
我嘗試執行以下操作,但沒有奏效:
<style>
.img-container {
width: 40px;
height: 40px;
}
.pic {
width: 100%;
max-width: 100%;
}
</style>
<div class="img-container">
<img src="image_path" class="pic" />
</div>
我被迫使用overflow: hidden
,它基本上會裁剪一半。 有沒有辦法用 jQuery 或 Bootstrap 實現相等的寬度和高度?
你確定這不是你想要的嗎? 圖像將很好地縮放到容器,並且空閑空間由容器的背景填充。 此外,無論尺寸如何,圖像都完美居中。
.img-container { width: 40px; height: 40px; border: 1px solid; position: relative; } .img-container img { width: 100%; height: auto; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }
<div class="img-container"> <img src="http://lorempixel.com/400/200" alt="Random image"> </div>
使用<img>
標簽無法實現這一點,因為不成比例地更改初始圖像尺寸總是會導致丑陋的圖像縮放。 相反,您可能會發現這里更適合使用background-image
<div class="item"></div>
.item {
background: url('path/to/your/image.jpg') center center no-repeat;
-webkit-backround-size: cover;
backround-size: cover;
width: 40px;
height: 40px;
}
它不會給你 100% 想要的效果,但至少你將能夠很好地控制你的圖像容器大小,並且你的圖像仍然會占據所有它而不會改變縱橫比。
UPD :如果您在評論中討論的用戶個人資料圖片,您肯定需要尋找更復雜的解決方案。 可以肯定的是,它已經在您之前發明了。
要在不拉伸的情況下用圖像完全填充容器,您有 2 個選項:
用於背景圖像: background-size: cover;
#image { outline: 2px solid red; width: 550px; height: 150px; position: relative; background: url('http://i.imgur.com/HNj6tRD.jpg'); background-repeat: no-repeat; background-size: cover; float:left; }
<div id="image" alt=image></div>
對於常規圖像使用: object-fit: cover;
加overflow:hidden
在容器上。 使用object-position: 0% 0%;
用於定位。
#img { width: 100%; height: 100%; object-position: 0% 0%; -o-object-fit: cover; object-fit: cover; } #cover { width: 550px; height: 150px; outline: 2px solid red; overflow: hidden; }
<div id="cover"><img id=img src="http://i.imgur.com/HNj6tRD.jpg"></div>
所有將具有類 pic 的圖像的大小為 40px x 40px 而不拉伸(即實際圖像大小,但會用空白填充其周圍的區域)
.pic {
width: 40px; //your image size
height: 40px; //your image size
/*Scale down will take the necessary specified space that is 40px x 40px without stretching the image*/
object-fit:scale-down;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.