dshamis317
dshamis317

Reputation: 91

Fully fit images with different dimensions into the same sized div

this is a weird one because there are a lot of aspects out of my control. I'm working with a custom image carousel where the image is a background image and the containing div has a set width and height (these can't be changed) but things like background-position and background-size I can manipulate.

The problem comes from images of varying aspect ratios. If I just try manipulating the width and height, the image gets cropped. Trying something like:

background-size: 100%

will work with images that are wider, while:

background-size: auto 100%

works better for taller images.

background-size: cover

crops both sizes and in a perfect world I'd like to find a CSS only solution. Does anyone have any ideas on how to make images of both aspect ratios completely fit into the same sized div?

Upvotes: 1

Views: 595

Answers (1)

misterManSam
misterManSam

Reputation: 24712

You're looking for the contain value:

contain

This keyword specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.

body > div {
  height: 500px;
  width: 500px;
}

.tall {
  background: #F00 url(http://www.placehold.it/500X1000) center no-repeat;
  background-size: contain;
}
.wide {
  background: #F90 url(http://www.placehold.it/1000X500) center no-repeat;
  background-size: contain;
}
<h2>I contain a tall image!</h2>
<div class="tall"></div>

<h2>I contain a wide image!</h2>
<div class="wide"></div>

Upvotes: 1

Related Questions