Hiding part of an image

I have an image 500x348px which has a lot of white space around it that I wish to display without the white space.

It comes form an API so I can’t edit it.

I thought I needed to use clip-path: polygon(23% 1%, 77% 1%, 77% 41%, 23% 41%); This hides all the white space (plus a bit more) but the image still takes up the whole 500x348px. Can I make it so the image only takes up the space of the clipped area? I tried overflow: hidden; without success.

2 Likes

Another option would be to stick it inside a container with the desired width and height and position the image inside that div with object-fit / object-position.

As an example, if the part of the image you wanted to show was 360px x 240px and there was 40px of whitespace on the top and left, you could place the image in a div and use CSS like this:

div {
  width: 360px;
  height: 240px;
}

img {
  width: 100%;
  height: 100%;
  object-fit: none;
  object-position: -40px -40px;
}
3 Likes

Yey, @ralphm, that gives me something to play with! Thanks.

1 Like

Actually, I just remembered you don’t need the div at all. You could just do all this with the image itself:

img {
  width: 360px;
  height: 240px;
  object-fit: none;
  object-position: -40px -40px;
}

So object-fit + object-position seems like the perfect solution.

4 Likes

Perfetto!

2 Likes

Next job will be to make it responsive…

Ouch! With friends like you …

I was going to give up on this, but then came up with this. I’m sure @PaulOB could do far better, but one’s gotta try …

2 Likes

Using SVG:

3 Likes

Thanks, chaps. Actually, it looks like the usual trick of changing width to max-width and height to max-height and adding width: 100% and height: auto almost works. :slight_smile:

1 Like

The svg version from @Archibald looks the neatest.

I think all angles have been covered here already. You could use percentages but it’s messy.

1 Like

Yes, @Archibald and @PaulOB — both nicer solutions than mine. Fun to play around, though!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.