skip to Main Content

I have an image that I want to be seen well in responsive mode, unfortunately, due to its large width, its height is too small on the phone!
If I give it this:

object-fit: cover;
min-height: 250px;

It is not an accurate method and it may not be displayed correctly in some sizes.

Is it possible to specify a range of width 10% of the image from the sides, and allow the image to zoom only up to that 10%?
with object-fit: cover;

And after that, by reducing the width of the browser, the height of the image will be reduced

my code:

img.ihero {
width: 100%;
}
<a href="https://example.com/">
<img class="ihero" src="https://i.sstatic.net/fzY3Uxj6.jpg">
</a>

2

Answers


  1. Yes, you can achieve what you want to achieve, but you do need media queries to implement different styling at different viewport widths.

    Your source image is 2560×600 pixels in size, but I’m assuming that you want to treat it as a @2x image, so in terms of CSS pixels we consider it to be 1280×300. With 10% cropped off each side, the image would be 2048×600, or 1024×300 in CSS pixels.

    1. The overall strategy is to wrap the image in a container, constrain the container in various ways, set the image to fill the container and set object-fit: cover so that it will crop automatically.
    2. At widths below 1024 pixels we constrain the container’s aspect-ratio to 1024/300. 20% of the image width is cropped, 10% from each side.
    3. At widths between 1024 and 1280 pixels we constrain the container’s height to 300 and unconstrain the aspect-ratio. The crop varies smoothly from 20% at 1024 pixels to 0% at 1280 pixels.
    4. At widths above 1280 pixels, both height and aspect-ratio can both be auto (or initial). The image is not cropped.

    A snippet to demonstrate. After running it, make sure to use the full page link to test the responsive behaviour.

    body {
      margin: 0;
    }
    
    a.ihero {
      aspect-ratio: 1024/300;
      border: 2px solid red;
      display: block;
    }
    
    @media (min-width: 1024px) {
      a.ihero {
        aspect-ratio: initial;
        height: 300px;
      }
    }
    
    @media (min-width: 1280px) {
      a.ihero {
        height: auto;
      }
    }
    
    a.ihero img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      display: block;
    }
    <a class="ihero" href="https://example.com/">
      <img src="https://i.sstatic.net/fzY3Uxj6.jpg">
    </a>

    After running this snippet, make sure to use the full page link to test the responsive behaviour.

    Login or Signup to reply.
  2. width: calc(100vw - 10%);
    height: auto;
    

    You can also use transform: scaleX(0.9) or scale(0.9) as a temporary measure. Or use JS if nothing works in worst case.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search