Chris Spittles
Chris Spittles

Reputation: 15359

How to do proportionate image gallery supporting both horizontal and vertical aspects?

I'm trying to make an image remain proportionate even when the viewport or parent element's aspect ratio changes.

So far I have this fiddle which utilises certain techniques for setting an image as a fullscreen background. Unfortunately once it gets to a certain size it overflows and parts of the image are hidden.

HTML

<div class="full-screen">
    <img src="http://placehold.it/350x150" />
</div>

CSS

.full-screen {
      position: fixed; 
      top: -50%; 
      left: -50%; 
      width: 200%; 
      height: 200%;
}
.full-screen img {
      position: absolute; 
      top: 0; 
      left: 0; 
      right: 0; 
      bottom: 0; 
      margin: auto; 
      min-width: 50%;
      min-height: 50%;
}

Ideally I never want the image to crop, I always want it to occupy either it's full width or full height depending on the aspect ratio.

Here's an image which will hopefully make it easier to understand:

enter image description here

If this isn't possible with CSS alone, how could you calculate the resize using jQuery?

I've looked at posts on here like his one:

Proportionally resize image based on parent div size

Suggesting I set the height of the image to auto, but this doesn't seem to work.

Upvotes: 2

Views: 100

Answers (1)

Nick Rice
Nick Rice

Reputation: 1223

Instead of min-width and min-height, use max-width and max-height in .full-screen img.

min-width means the size won't shrink below that width (and the same for height, of course).

Upvotes: 1

Related Questions