Vilarix Vilarix - 6 months ago 247
HTML Question

Maintain image aspect ratio in carousel

I am using Bootstrap to create a carousel, I have large images so when the screen is smaller than the image, the ratio is not kept.

How could I change that?

Here is my code:

.carousel .item {
height: 500px;
}
.carousel img {
position: absolute;
top: 0;
left: 0;
min-width: 100%;
height: 500px;
}


http://jsfiddle.net/DRQkQ/

I need the image to fit 100% width but keep its height of 500px (I think it's 500px) this should mean that on smaller screen we don't see the far left and far right of the image.

I tried containing the image in a div and add

overflow: hidden;
width: 100%;
height: 500px;
display: block;
margin: 0 auto;


But it doesn't work

Thank you!

Answer

The issue lays here, on bootstrap CSS:

img {
  max-width: 100%;
  width: auto   9;
  height: auto;
  vertical-align: middle;
  border: 0;
  -ms-interpolation-mode: bicubic;
}

Having set max-width: 100%; the image won't be any larger than the viewport. You need to override that behavior on your CSS:

.carousel img {
  position: absolute;
  top: 0;
  left: 0;
  min-width: 100%;
  height: 500px;
  max-width: none;
}

Note the max-width: none; added at the bottom. This is the default max-width value and unsets the limit.

Here's your fiddle updated.