I have a container-DIV with
- Height: 400px;
- Width: 80%;
I have a set of images with different sizes.
How do i specify that the image:
- Always maintains it's aspect ratio
- Always fills the container-div
- Aligns to the center of the container-div
- When the div is wider than the image
- width of the image is stretched or squeezed to div-width
- height of the image is automatically cropped to maintain aspect ratio
- When the div is taller than the image
- height of the image is stretched or squeezed to div-height
- width of the image is automatically cropped to maintain aspect ratio
Is this possible using only CSS (no JS)? If easier, JS is also an option. The image can be set as background or as an explicit img tag inside the div.
Examples:
- When the window width is 500px, the div will be 400px(W) & 400px(H)
- An image of 1000px(W) & 500px(H) should be squeezed to 800px(W) x 400px(H) and 200px should be cropped from both the left and the right.
- When the window width is 1500px, the div will be 1200px(W) & 400px(H)
- an image of 1000px(W) & 500px(H) should be streched to 1200px(W) x 600px(H) and 100px should be cropped from both the top and the bottom.
Fiddle at: http://jsfiddle.net/fnbL757q/
HTML:
<div id="container">
<img id="image" src="https://lh4.googleusercontent.com/-jKo72r_w7e4/UlFMCWDx-dI/AAAAAAAAIl0/whCcucpCc_I/s1024/IMG_5364_LQ.jpg" />
</div>
CSS:
#container {
max-height: 400px;
width: 80%;
border: 1px solid black;
margin: 0 auto 0 auto;
overflow: hidden;
}
#image {
}
Thanks in advance.