JensB
JensB

Reputation: 6850

Scale down image to fit into div, but never scale up

I have several images with very varying dimensions. Some images may be as small as 50x100 and others as big as 4000x4000.

I want to show these images in their original size (never bigger), or scaled down to just fit inside the browser window.

Using the background image property I have gotten the images to always fit inside the browser, but I can't stop them from up-scaling if the browser is bigger than the image:

 <div class="slide-pane" style="background-image: url(<insert url to image here>);"></div>

.slide-pane {
    background-repeat: no-repeat;
    background-size:auto;
    position: absolute;
    background-position: center;
    background-repeat: no-repeat;
    height: 80%;
    width: 80%;
}

I have found these Javascript/Jquery solutions:

But I'm hoping there are some CSS only solutions.

Upvotes: 1

Views: 406

Answers (2)

Robin Whittleton
Robin Whittleton

Reputation: 6339

If they’re content images (and not there for style) then you’re better off using an <img> element in the page. If you do that then you can give it img { max-width: 100%; } in your CSS. This has the added benefit of working in IE8 (unlike background-size).

Upvotes: 1

S..
S..

Reputation: 5758

max-height:100%;
max-width:100%;
height:auto;

Apply that to an img not an elements background image. Background images don't have full browser support for max width height. You could use background-size set to 100% 100% but I'd recommend using an img for better css control and accessibility.

Upvotes: 3

Related Questions