Search code examples
cssimageresizecenteringfluid-layout

Fluid dynamic image centered in div - resize with div immediately


So, I have a fully fluid web page. There is a parent DIV with width:100%, and inside an IMAGE with style:

<div>
     <img src="image.png" alt="" />
</div>

<style>
    div{ width:100% }
    img{
      display: block;
      margin: auto;
      max-width: 100%;
    }
</style>

Image is centered in div. I do not know the size of image, but it is always smaller than parent DIV, so there is white space from img borders to div borders. Now, when you resize the browser, the image is not resizing until the parent DIV reaches the borders of the image.

If image would have style width:100%, then it would stretch beyond real size...

I would like this image to scale with div immediately when browser window is resized. If image canvas would be 100% of parent div, the behaviour would be like I wanted (the image would resize immediately because image would be 100% od div's width). But I can not make images to be like that...


Solution

  • I don't think it's possible with pure CSS, but you can use some jQuery - http://jsfiddle.net/UcV7y/

    var ratio = $("img").parent().width() / $("img").width();
    
    $(window).resize(function() {
        $("img").width( $("img").parent().width() / ratio + "px" );
    });
    ​