Search code examples
ruby-on-railsimageflexboxscalingcentering

Resize image into square div keeping aspect ratio


I need in my application to insert images into square div of given size and I want them to show full, without cropping any part of it. At the moment I've got a javascript code that if the image is portrait (height > width) then set the height to 100% and width to auto, if it is landscape (width > height) set width to 100% and height to auto

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

This is a link where I tried to reproduce my code(it's in erb and coffee because I'm developing a rails application, and I don't know why but the images are not centered inside the div(in my application this code works great!)

This is my code in 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>

This is Coffee

$('.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')

And this is the scss

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

I started using flex for my layout, so my question is, Is possible to achieve this behavior with flex component? Maybe without all JS code and the -9999 in css

Thanks


Solution

  • You could use max-height: 100% and max-width: 100% on the .image-resize, and I believe it would give you the results you're after. If you want to be safe, you could also add width: auto and height: 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>