resize view width, preserve image aspect ratio with CSS
Asked Answered
I

2

1

I got interested in this from noticing how images are scaled when you resize the browser on "lightbox"ed images on Google+: https://plus.google.com/.

below is a jsfiddle which when you resize the browser width, only resizes the image width and aspect ratio is lost: http://jsfiddle.net/trpeters1/mFPTq/1/

Can someone help me figure out what the CSS would look like to the preserve aspect ratio of this image?

If you don't want to view the jsfiddle, here's the HTML:

<div id="imgWrapper" >
  <div id="titleContainer">title container
  </div>
  <div id="imgContainer"  >    
        <img id="mainImg" src="https://lh4.googleusercontent.com/-f8HrfLSF2v4/T609OOWkQvI/AAAAAAAAGjA/waTIdP4VkMI/s371/impact_of_early_exposure_to_D%26D.jpg">    
  </div>
</div>​

here's the CSS:

 #imgWrapper{
  background:gray;
  width:80%;
  height:80%;
  border-radius:5px;
  border:1px solid gray;
 }
 #imgContainer{
   width:100%;
   height:100%;    
 }
#titleContainer{
  background:yellow;
  border-radius:5px;
  border:1px solid gray;
}
#mainImg{
  width:100%;
  height:61.8%;    
}​
Inebriety answered 11/5, 2012 at 21:46 Comment(0)
R
5

If I'm understanding you correctly, simply remove the height on the img all together.

http://jsfiddle.net/mFPTq/2/

#mainImg{
    width:100%;
    /* NO HEIGHT height:61.8%; */
}​
Russom answered 11/5, 2012 at 21:48 Comment(4)
remove the height from which element? your fiddle is the same as mine.Inebriety
Copied the wrong URL, remove the height from the image. Fiddle link updated.Russom
-@JamesMontagne, thanks, for completeness can you point out the CSS change in your answer?Inebriety
This solution is fine unless the picture has a taller aspect ratio than the screen. In that case, the lower part of the picture won't be visible. And max-height limits the height, but messes up the aspect ratio.Goldston
C
0

Sometimes the browser will scale height... I had this issue, so all I did to fix was this:

 <style> 
 img{ max-width:100%; height:auto; }
 </style>
Congo answered 26/5, 2014 at 21:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.