将图像调整为正方形 div 并保持纵横比

Resize image into square div keeping aspect ratio

我需要在我的应用程序中将图像插入给定大小的正方形 div 中,并且我希望它们显示完整,而不裁剪任何部分。目前我有一个 javascript 代码,如果图像是纵向(高度 > 宽度),则将高度设置为 100%,宽度设置为自动,如果是横向(宽度 > 高度),则将宽度设置为 100 % 和高度自动

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

这是一个 link 我试图重现我的代码的地方(它在 erb 和 coffee 中,因为我正在开发一个 rails 应用程序,我不知道为什么,但图像是不在 div 的中心(在我的应用程序中这段代码工作得很好!)

这是我在 rails

中的代码

再培训局

<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>