簡體   English   中英

將圖像調整為方形div並保持寬高比

[英]Resize image into square div keeping aspect ratio

我需要在我的應用程序中將圖像插入給定大小的正方形div中,並且希望它們顯示完整,而不裁剪任何部分。 目前,我有一個javascript代碼,如果圖像為縱向(高度>寬度),則將高度設置為100%,寬度設置為自動;如果圖像為橫向(寬度>高度),則將寬度設置為100%,高度設置為汽車

http://jsfiddle.net/z7L6m2sc/583/

這是我嘗試重現代碼的鏈接(由於我正在開發Rails應用程序,因此它在erb和coffee中,並且我不知道為什么,但是圖像不在div內部居中(在我的應用程序中,此代碼很好用!)

這是我在Rails中的代碼

ERB

<div class="img">
  <% if i.insertion_images.length > 0 %>
    <%= image_tag(i.insertion_images[i.first_img].image.url(:medium), class: 'last_img')%>
  <% end %>
</div>

這是咖啡

$('.last_img').on 'load', ->
      natHeight = $(this).get(0).naturalHeight
      natWidth = $(this).get(0).naturalWidth
      if (natWidth > natHeight)
        $(this).css( 'width','100%')
        $(this).css( 'height','auto')
      else #if (natWidth < natHeight)
        $(this).css( 'height','100%')
        $(this).css( 'width','auto')

這是scss

img {
      width: 200px;
      height: 200px;
      overflow: hidden;
      position: relative;
      last_img {
        position: absolute;
        top: -9999px;
        bottom: -9999px;
        left: -9999px;
        right: -9999px;
        margin: auto;
      }
    }

我開始在布局中使用flex,所以我的問題是,是否可以通過flex組件實現此行為? 也許沒有所有的JS代碼和CSS中的-9999

謝謝

如果您不介意將圖片設置為背景,則可以使用CSS進行此操作。

 .bg-image{ height: 300px; width: 300px; background-color: red; background-size: contain; background-repeat: no-repeat; background-position: center; display: inline-block; } 
 <div class="bg-image img-1" style="background-image: url(http://s.hswstatic.com/gif/landscape-photography-1.jpg)"></div> <div class="bg-image img-2" style="background-image: url(https://i.pinimg.com/736x/05/1c/11/051c110d463b1c4afb11ca003a6237a3--nice-girl-beautiful-body.jpg)" ></div> 

您可以在.image-resize上使用max-height: 100%max-width: 100% ,我相信它會為您提供想要的結果。 為了安全起見,您還可以添加width: autoheight: auto

 .img-container{ height: 300px; width: 300px; overflow: hidden; background:red; position: relative; } .image-resize { max-width: 100%; max-height: 100%; height: auto; width: auto; } 
 <div class="img-container"> <img src="http://s.hswstatic.com/gif/landscape-photography-1.jpg" class="image-resize"/> </div> <hr> <div class="img-container"> <img src="https://i.pinimg.com/736x/05/1c/11/051c110d463b1c4afb11ca003a6237a3--nice-girl-beautiful-body.jpg" class="image-resize"/> </div> 

暫無
暫無

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

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