3

How to restrict the height of an image to its parent container whose height is specified in terms of percentages?

I want the image to span over the parent if image width/height > parent width/height. and image to be center aligned to parent if image width/height < parent width/height. In any case I dont want the image to be stretched[vertically/horizontall.]

html, body{
    width:100%;
    height:100%;
}

#top{
    height:10%;
}

#middle{
    height:80%;
}

#bottom{
    height:10%;
}

img{
    width: how much?
    height: how much?
}

<html>
    <body>
        <div id="top">I am top</div>
        <div id="middle">
            <img src="/images/abc.jpg" />
        </div>
        <div id="bottom">I am bottom</div>
    </body>
</html>
Aditya Kappagantula
  • 564
  • 1
  • 7
  • 21
  • How can I request that this question be UNMARKED as duplicate?? – Aditya Kappagantula Mar 17 '14 at 01:24
  • Reopen vote. But it _is_ a dup: http://stackoverflow.com/a/19193223/2888561 – bjb568 Mar 17 '14 at 18:43
  • 1
    How is this a duplicate question? I wanted the parent to be a generic container [without fixed width or height!] More over, the solution I approved is using width:"auto" and height:100% to avoid image stretching. The questions suggested gives solution for a fixed width and height parent container. – Aditya Kappagantula Mar 18 '14 at 07:12
  • The container doesn't matter, the problem is the contained. `width: auto` _should_ be default, anyway. – bjb568 Mar 18 '14 at 07:13
  • I am afraid but that is not the solution that I want And width auto was not default on Chrome latest browser. – Aditya Kappagantula Mar 18 '14 at 07:14

1 Answers1

15
height: 100%;
width: auto;

Just define the image height as a percentage, auto width will keep it in proportion.

bjb568
  • 11,089
  • 11
  • 50
  • 71