0
votes

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.

1
Paste some code dude.Java_User
Nice explanation, but unfortunately no code to see???. Post you code or make a fiddle of your problemRicha

1 Answers

0
votes

You can try with something like this:

#container-DIV {
    background-image:url('your_image.png');
    background-repeat:no-repeat;
    background-size:cover;
}

css rule background-size:cover will, according to http://www.w3schools.com/cssref/css3_pr_background-size.asp:

Scale the background image to be as large as possible so that the background area is completely covered by the background image. Some parts of the background image may not be in view within the background positioning area

Demo JSFiddle: http://jsfiddle.net/lparcerisa/p3fxmh78/