Laxo Laxo - 1 year ago 43
HTML Question

Maintaining Aspect Ratio with 100% Width & Height (Cropping Overflow in CSS)

I'm working on full-screen background slideshow.

My question is: How can I set an image to take up the full screen and maintain aspect ratio?

Min-height and min-width work, but do not keep the aspect ratio when both are set. I want the image cropped with the full coverage of the container.

Diagram of Problem

I believe I need to have one dimension fixed, and the other to auto; given that the image dimensions and view-port dimensions are variable, I'm thinking I would need at least 2 sets of CSS rules, and javascript to calculate which one should be used. Is there a simpler way to do this?

I've drawn up a diagram illustrating my problem. The dark colors are the original images. The median colors are the desired effect. The lighter colors are the desired overflow from the scaled up image.

I'm working on a Ken-Burns effect full-screen background. I know I have to worry about transitions, but I'm hoping that I can handle that after.

Tutorial for Ken Burns Effect:

Solved: Thanks Maju for introducing me to background cover. Changing the images to divs and changing the javascript + css on the Ken Burns code from images to divs worked well. The script changes the element class, so you have to use Maju's CSS another way or change the script.

Answer Source

If you will use images in css background-image, you can set on any element background-size. And if I understand you right, you need something like:

.background {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-repeat: no-repeat !important;
  background-position: 0 0 !important;
  background-attachment: fixed !important;
  -webkit-background-size: cover !important;
  -moz-background-size: cover !important;
  -o-background-size: cover !important;
  background-size: cover !important;
<div class="background" style="background-image: url("></div>

Cover will affect image in the way that it will always cover the whole element with right aspect ratio.

There is also new css style, but it doesn't work in IE/ME.

For this reason I recommend to use divs with background-image.