1

Is there any Javascript library that could force an HTML node (mostly images and div) to keep their aspect ratio while resized?

This would be particularly useful to resize the height of an element when its width is constrained by the size of the window.

Note: if that can be done in pure CSS, I'm buying it!

Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261
  • http://techpp.com/2008/08/02/how-to-resize-the-images-using-css-without-losing-the-aspect-ratio/ and http://stackoverflow.com/questions/757782/how-to-preserve-aspect-ratio-when-scaling-image-using-one-css-dimension-in-ie6 – Derek 朕會功夫 Jun 21 '12 at 22:05
  • [Here's an article about a somewhat more complicated technique.](http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/) – Pointy Jun 21 '12 at 22:16
  • @Derek only works with images – Matthieu Napoli Jun 22 '12 at 09:52

1 Answers1

2

You mean like this?

http://jsfiddle.net/DerekL/J2s3C/

Here's the code:

img{
    width: 100%;
    height: auto;
}

For other elements, it will be a bit more complicate.

Here a second demo: http://jsfiddle.net/DerekL/5BgXk/ :

<div id="wrapper"><div id="content"></div></div>

#wrapper {
    position: relative;
    padding-bottom: 33.33%; /* Set ratio here */
    height: 0;
}
#content {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: green;    
}
Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • Well it will only work with images as they have a native aspect ratio. `div` don't have aspect ratios so it's impossible for the browser to set an appropriate height. – Matthieu Napoli Jun 22 '12 at 09:54
  • I mean, if in your example you replace `img` with `div`, where/how would you set the wanted aspect ratio? – Matthieu Napoli Jun 22 '12 at 09:54
  • @Matthieu - Here's how you do it with elements other than ``: http://jsfiddle.net/DerekL/5BgXk/ – Derek 朕會功夫 Jun 22 '12 at 22:36
  • Great! It worked, I only had to add `height: 100%` also on the image *inside* the `div` keeping the ratio. – Matthieu Napoli Jun 23 '12 at 09:46
  • I edited your answer to add the second code snippet. I had some problems with Safari and it was fixed setting `height: 100%` instead of `0` for the `#wrapper`. – Matthieu Napoli Jun 26 '12 at 21:14
  • Oops, actually no the `height: 0` is best, it's just that in Safari any `img` inside the content without a fixed size will have to have `position: absolute` to be displayed (else it will have height=0 because of the #wrapper)... But that `position: absolute` is not good for me... I'm looking for a better solution – Matthieu Napoli Jun 26 '12 at 21:35
  • I asked a separate question here: http://stackoverflow.com/questions/11276367/forcing-aspect-ratio-with-css-doesnt-work-on-safari (for anyone having the same problem) – Matthieu Napoli Jun 30 '12 at 18:01