Reputation: 838
I have a webpage which will show different images at different times. Some images are wider than the webpage, some are taller, some are both. Is there a way using CSS to limit to the larger of the two (for example if the image was too wide for the screen, the image would reduce both height and width to keep the aspect ratio the same until the width fit in. The same scenario if the height is too tall).
Ive managed to reduce an image which was originally ~1500px x 2000px so its width fits on, but the scroll bar is still needed to see the bottom part of the image. Ive achieved this by have a container div with the following:
#container {
min-width: 740px;
max-width: 1000px;
min-height: 100%;
margin-left: auto;
margin-right: auto;
margin-top: 10px;
}
and then setting the div containing the image to width:100% and height:100%. The width changes to fit, but the height doesnt!
edit: using the two examples given in the answers below i get:
which is just constraining the image to a certain size which I could do just by setting the width and height properties of the image. I want it to maximize to the screen while maintaining aspect ratio, so if its a wide image the entire width will be shown (albeit with blank space above and below to maintain aspect ratio) and likewise if it is a tall image, the entire height of the image is shown with blank space around the sides. Sorry if my original question didnt get this point across succinctly!
Upvotes: 0
Views: 283
Reputation: 11031
This is probably what you want:
HTML:
<div id="container" style="background-image: url('pic1.jpg');"></div>
CSS:
#container {
width: 600px;
height: 500px;
overflow: hidden;
background-size: cover;
background-position: center center;
}
But in any case if you want to fill fixed container with variable image size you will have to sacrifice some of the image to overflow the content boundaries if you want to maintain image's aspect ratio.
Upvotes: 1
Reputation: 41958
This cannot be achieved with img
tags without adding Javascript. Instead of:
<img src="myimage.jpg">
Use
<div class="preview" style="background-image:url(myimage.jpg)"></div>
And then add some CSS:
.preview {
background-size:contain;
background-repeat:no-repeat;
width:300px;
height:300px;
}
Upvotes: 1