簡體   English   中英

在div高度內適合圖像,但在保持寬高比的同時將水平內容居中

[英]Fit image inside div height but center horizontal content while maintaining aspect ratio

我應如何編輯以使圖像在容納的<figure>高度內水平居中?

縮略圖將為75px x 75px。 上傳的圖片可能會有所不同,但通常約為4:3的比例,例如800px x 600px。


的HTML

<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-fitobject-position屬性,其作用類似於background-sizebackground-position ,但適用於imgvideo標簽。 它具有良好的跨瀏覽器支持 ,但不如上述方法好。 此示例已添加到codepen鏈接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM