[英]Fit image inside div height but center horizontal content while maintaining aspect ratio
我應如何編輯以使圖像在容納的<figure>
高度內水平居中?
縮略圖將為75px x 75px。 上傳的圖片可能會有所不同,但通常約為4:3的比例,例如800px x 600px。
<figure>
<img src="">
</figure>
figure {
background-color: #777;
display: inline-block;
text-align: center;
overflow: hidden;
height: 75px;
width: 75px;
vertical-align: top;
position: relative;
z-index: 1;
img {
position: absolute;
z-index: 5;
height: 75px;
width: auto !important;
top: 50%;
left: 50%;
transform:translate(-50%, -50%);
}
}
做到這一點並獲得良好的跨瀏覽器支持的最佳方法是使用background-image
而不是實際的圖像標簽。 看看這個codepen:
https://codepen.io/treyhakanson/pen/eGVVpr
基本上,使用background-size: contain
將使圖像受其最大尺寸限制,同時保持其寬高比,而background-position: center
將使圖像在其容器內居中。
如果您不能使用background-image
而必須使用img
標簽,請檢查object-fit
和object-position
屬性,其作用類似於background-size
和background-position
,但適用於img
和video
標簽。 它具有良好的跨瀏覽器支持 ,但不如上述方法好。 此示例已添加到codepen鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.