Fred
Fred

Reputation: 4947

How to stretch an image to fit screen and maintain aspect ratio using CSS?

See my example here - http://jsbin.com/kutobedo/1/edit

When you shrink the browser window, the image resizes correctly and maintains it's aspect ratio. However I want the image to always stretch to fill the screen, but in this case it never stretches beyond it's native resolution.

If I set width:100% instead of max-width. It will stretch the image to fit the width but if you shrink the window vertically, it will start to distort the image.

If I set height: 100% instead of max-height I get overflow/scrollbars instead.

So I'm a bit stuck! Please note the images will be of different aspect ratios and resolutions.

I suppose in the long run, this might not be a good idea as a 1024x768 image blown up on a 4k screen may look a little nasty. Still would like a solution for now though.

Upvotes: 0

Views: 4349

Answers (2)

user3581850
user3581850

Reputation: 31

With the property »cover« the image is scaled up to the entire background until the whole background is covered therewith. More at http://en.aufdemdach.org/css-en/css-center-background-images/

Example:

body{
   background: url("http://lorempixel.com/g/1000/1000/") no-repeat center center fixed;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
}

Upvotes: 1

demonofthemist
demonofthemist

Reputation: 4199

Set image as background of a div & use background-size:cover;. This will stretch it to fill screen without losing aspect ratio, no matter what are image dimentions are.

Upvotes: 2

Related Questions