简体   繁体   中英

Image resize in ratio when vertically resizing a browser window?

I have articles with display:table and an image wrapper inside with display:table-cell to achieve vertical and horizontal aligning of the images. The images are set to 80% width and height so when resizing the browserwindow the image should scale in ratio.

<article class="layer">
   <div class="wrap">
      <img src="whatever.jpg" alt="image"/>
   </div>
</article>

html, body, #content {
    margin: 0; padding: 0;
    height: 100%;
    width: 100%;
}

article.layer {
    position: relative;
    display: table;
    height: 100%;
    width: 100%;
}

article.layer img {
   max-width: 80%;
   max-height: 80%;
}

div.wrap {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

What I'm trying to do is keep the image always displayed fully. So I don't want it to be cut off when resizing the browserwindow. This works fine right now when I resize the browserwindow horizontally, however it doesn't when resizing it vertically.

Here is a sample: http://jsbin.com/ugumuj/10/edit#preview

Is there a way to achieve the same thing when resizing the browserwindow vertically as well? I'd love to do it in a pure CSS way but I'd also use jQuery or Javascript to do so.

Any ideas? Thank you in advance.

javascript:

window.onresize = function(){
      $('article.layer img').css({
        maxHeight: $('article.layer').height() * 0.8,
        maxWidth: $('article.layer').width() * 0.8
      });
    };

jQuery:

$(window).resize(function(){
  $('article.layer img').css({
    maxHeight: $('article.layer').height() * 0.8,
    maxWidth: $('article.layer').width() * 0.8
  });
});

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM