2017-10-21 91 views
-1

我想將圖像粘貼到底部,同時按比例放大以填充其父項並保持其寬高比。如何將img貼到底部,同時向上擴展以填充父項?

我知道如何做到這一點與背景圖像,但我希望它是一個<img>。 父級的大小未知。

有沒有辦法做到這一點沒有JavaScript?

該片段顯示我想要的。

div { 
 
    width: 100px; 
 
    height: 100px; 
 
    background-color: red; 
 
    margin: 10px; 
 
    background-repeat: no-repeat; 
 
    background-position: center bottom; 
 
    background-size: contain; 
 
} 
 
img { 
 
    width: 100%; 
 
    height: 100%; 
 
    object-fit: contain; 
 
}
<div> 
 
    <img src="http://via.placeholder.com/25x50" alt=""> 
 
</div> 
 
<div> 
 
    <img src="http://via.placeholder.com/50x25" alt=""> 
 
</div> 
 
What I want: 
 
<div style="background-image: url(http://via.placeholder.com/25x50)"> 
 
</div> 
 
<div style="background-image: url(http://via.placeholder.com/50x25)"> 
 
</div>

+0

堅守窗口的底部? – crook

+0

堅持容器的底部。 – newcleus

+0

嗯,我相信指定'vertical-align:bottom'可能會工作 –

回答

1

只是object-fit一起使用object-position

div { 
 
    width: 100px; 
 
    height: 100px; 
 
    background-color: red; 
 
    margin: 10px; 
 
    background-repeat: no-repeat; 
 
    background-position: center bottom; 
 
    background-size: contain; 
 
} 
 
img { 
 
    width: 100%; 
 
    height: 100%; 
 
    object-fit: contain; 
 
    object-position: bottom; 
 
}
<div> 
 
    <img src="http://via.placeholder.com/25x50" alt=""> 
 
</div> 
 
<div> 
 
    <img src="http://via.placeholder.com/50x25" alt=""> 
 
</div> 
 
What I want: 
 
<div style="background-image: url(http://via.placeholder.com/25x50)"> 
 
</div> 
 
<div style="background-image: url(http://via.placeholder.com/50x25)"> 
 
</div>

+0

非常感謝你:) – newcleus

相關問題