Search code examples
jqueryhtmlcssresponsive-design

Responsive Image cropping


I have been trying to crop an image for screen sizes below 768px width. The image should crop equally from the left and right sides.

Here is an Example of the Image at full size (the dimensions of the image are 900px wide by 250px tall.:

Here is the cropped version I have been trying to create once the screen size is less than 768p wide. In this version the image is at 320px wide but it should start cropping at 768px:

Here is the HTML I have been using so far:

<div class="container">
    <div class="image-container">
        <img src="https://i.sstatic.net/kLxRs.jpg" />
    </div>
</div>

Here is the CSS:

.container {
    width: 1280px;
    max-width: 100%;
    min-width: 768px;
}

.image-container {
    width:100%;
}

img {
    max-width:100%;
    height:auto;
}

@media only screen and (max-width:768px) {
    .image-container {max-width:768px; overflow:hidden;}
}

Here's a fiddle I have been using to try and create this: http://jsfiddle.net/QRLTd/

Is it possible to crop an image from both the left and right sides at the same time?


Solution

  • On the img styles use the object-fit property with cover (or contain) value:

    .image-container {
      height: 180px; /* or any desired height on the parent */
    }
    
    img {
      display: block;
      width: 100%;
      height: 100%;
      object-fit: cover;  /* cover | contain */
    }
    <div class="image-container">
      <img src="https://i.imgur.com/H7cpsLK.jpg" alt="Gym cardio training" />
    </div>