How to vertically center a responsive clipped image?

132 Views Asked by At

I'm trying to vertically center an image that is clipped. The image is responsive. On mobile, the image is full-size and looks good. But, when the browser gets extended say for a laptop, the entire bottom half of the image is cropped off and nothing gets cropped at the top.

I tried playing around with the numbers in CSS. If the image is around 800px wide, it shows better but still, all clipping is done at the bottom.

Any ideas that will get the image to center vertically and remain responsive would be greatly appreciated. Thanks!

HTML:

  <div class="image-wrap" id="wrapper">
      <img src="cropped-img.jpg" alt="Oceanside Pier">
  </div>

CSS:

.image-wrap {
    max-height: 450px;
    overflow: hidden;
    max-width: 100%px;       
    -webkit-transition: max-width .5s ease-out;  /* Saf3.2+, Chrome */
    -moz-transition: max-width .5s ease-out;  /* FF4+ */
    -ms-transition: max-width .5s ease-out;  /* IE10? */
    -o-transition: max-width .5s ease-out;  /* Opera 10.5+ */
    transition: max-width .5s ease-out;
}

    .image-wrap img {
        width: 100%;
        -webkit-transition: margin-top .5s ease-out;  /* Saf3.2+, Chrome */
        -moz-transition: margin-top .5s ease-out;  /* FF4+ */
        -ms-transition: margin-top .5s ease-out;  /* IE10? */
        -o-transition: margin-top .5s ease-out;  /* Opera 10.5+ */
        transition: margin-top .5s ease-out;
    }

@media only screen and (min-width: 100%px) {
    .image-wrap { max-width: 100%; }
}

JavaScript:

$(document).ready(function() {
 
    var imageHeight, wrapperHeight, overlap, container = $('.image-wrap');  
 
    function centerImage() {
        imageHeight = container.find('img').height();
        wrapperHeight = container.height();
        overlap = (wrapperHeight - imageHeight) / 2;
        container.find('img').css('margin-top', overlap);
    }
     
    $(window).on("load resize", centerImage);
     
    var el = document.getElementById('wrapper');
    if (el.addEventListener) {  
        el.addEventListener("webkitTransitionEnd", centerImage, false); // Webkit event
        el.addEventListener("transitionend", centerImage, false); // FF event
        el.addEventListener("oTransitionEnd", centerImage, false); // Opera event
    }
});
1

There are 1 best solutions below

1
MuhMarigo On

If i get right what you want to do, try commenting your js to center the image and use the following style

.image-wrap img {

    object-fit:cover;//you can also try "contain" here
    object-fit:center;

    width: 100%;
    -webkit-transition: margin-top .5s ease-out;  /* Saf3.2+, Chrome */
    -moz-transition: margin-top .5s ease-out;  /* FF4+ */
    -ms-transition: margin-top .5s ease-out;  /* IE10? */
    -o-transition: margin-top .5s ease-out;  /* Opera 10.5+ */
    transition: margin-top .5s ease-out;

}

http://caniuse.com/#search=object-fit