1

I have an absolutely positioned div with a percentage height and an image in it. That image has a height of 100% and width of auto. When the height of the viewport is adjusted the absolute div will not adjust it's width and the images will either get cut off or you'll see the background of the div.

Example: http://jsfiddle.net/Y5Cr7/

CSS

div {
    position: absolute;
    overflow: hidden;
    height: 50%;
    bottom: 80px;
    left: 5%;
    background: blue;    
}

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

HTML

<p>adjust the height of the viewport</p>

<div>
    <img src="http://lorempixel.com/400/200" />
</div>
AndrewK
  • 13
  • 2
  • Here's [a link to an answer with a JS hack](http://stackoverflow.com/a/16864468/1846192) which [will fix your issue](http://jsfiddle.net/Y5Cr7/6/). The other answers in the thread might be worth reading too, it seems to be impossible to fix with CSS only. Here's a link to [an answer which sheds some more light on why things behave they way they behave](http://stackoverflow.com/a/5251088/1846192). – Mathijs Flietstra Jan 10 '14 at 20:04
  • Thanks Mathijs. I searched and searched for similar issues like this. But it looks like I could not come up with the right keywords in my search to get me the one you referenced. – AndrewK Jan 10 '14 at 20:20

1 Answers1

0

The div's width won't correspond to any changes in its height, unlike an img (in addition, the div's implicit width right now corresponds to the width of the viewport).

I see two options here...

  1. Media queries
  2. JavaScript

A library (such as jQuery) might be your best bet (here's the jsfiddle):

$(window).resize(function() {

    var imgWidth = $('img').outerWidth();

    $('div').css({
        'width':imgWidth
    });

});
Josh Beam
  • 19,292
  • 3
  • 45
  • 68