簡體   English   中英

使用純CSS進行圖像處理

[英]Image manipulation with pure CSS

我有以下圖片

<div class="product-main-img">
    <img src="@Model.ImageUrl" alt="@Model.Name" />
</div>

該圖像可以大於其容器,也可以小於其容器。 當較小時,我需要將其垂直和水平居中,但如果較大,則需要將其包含在內並將較短的一側居中。

我可以單獨執行此操作,並查看需要使用JavaScript來應用哪種樣式; 但是我有點想用純CSS解決它。 任何想法?

假設容器具有指定的尺寸( 因為您提到img可能更大或更小 )。

因此,對容器使用flex( 允許將其子元素居中 )向圖像添加min-widthmax-height

 .product-main-img { width: 300px; height: 150px; border:1px solid black; display:flex; flex-direction:column; align-items:center; justify-content:center; } .product-main-img img { max-width: 100%; max-height: 100%; } 
 <div class="product-main-img"> <img src="http://dummyimage.com/400x100" alt="@Model.Name" /> </div> <div class="product-main-img"> <img src="http://dummyimage.com/100x200" alt="@Model.Name" /> </div> <div class="product-main-img"> <img src="http://dummyimage.com/200x100" alt="@Model.Name" /> </div> <div class="product-main-img"> <img src="http://dummyimage.com/400x200" alt="@Model.Name" /> </div> 

一種簡單的方法是將圖像設置為<div>background-image ,然后使用background-position: centerbackground-size: contain使其適合容器。 例如:

 .image-container { border: 2px solid black; width: 100px; height: 100px; background-position: center; background-repeat: no-repeat; background-size: contain; } 
 <div class="image-container" style="background-image: url(https://lorempixel.com/400/200/cats/1/)" ></div> <br> <div class="image-container" style="background-image: url(https://lorempixel.com/200/400/cats/1/)" ></div> 

暫無
暫無

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

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