简体   繁体   中英

Scale div proportionally to fit viewport

I have written a small function that proportionally reduces the size of a div until it's height is the same as the viewport. This works perfectly. I have 2 issues I'd like to fix

  1. Is there a cleaner way of doing this?
  2. Once the height of the viewport is reduced it doesn't scale back up when the viewport is increased.

The objective behind the function is so that the container div is never higher than the viewport. This needs to be controlled by setting the width of the container as it contents are responsive. I've used a simple image with a width of 100% for demonstration purposes. I haven't used vh or vw due to lack of browser support. I need to support IE8.

Demo Jsfiddle

function setImageViewPointHeight() {

  // get current viewport height
  var targetHeight = $(window).height();

  // get current container height
  var containerHeight = $('.container').height();

  // get current container width
  var containerWidth = $('.container').width();


  // only set width if container is higher than viewport
  if (containerHeight > targetHeight) {

    // keep reducing container height/width value by 0.1% until target is reached
    while (containerHeight > targetHeight) {
      containerHeight = containerHeight - (containerHeight * .01);
      containerWidth = containerWidth - (containerWidth * .01);
    }

    // now we have desired calculated width
    $('.container').width(containerWidth + 'px');
  }

}

Taking into account browser support I don't see a problem with this approach. It seems clean enough from my perspective.

To fix your issue of container height adjustment when the viewport height is reduced simply set the width to initial when the function is invoked.

function setImageViewPointHeight() {

  $('.container').css('width', 'initial');   <-- add this

  var targetHeight = $(window).height();
  var containerHeight = $('.container').height();
  var containerWidth = $('.container').width();

  if (containerHeight > targetHeight) {
    while (containerHeight > targetHeight) {
      containerHeight = containerHeight - (containerHeight * .01);
      containerWidth = containerWidth - (containerWidth * .01);
    }
    $('.container').width(containerWidth + 'px');
  }

}

JSFiddle

I would use the vw vh CSS units to scale the div to the viewport.

https://css-tricks.com/viewport-sized-typography/

IE8 doesn't support it, but you can find polyfills for it https://github.com/saabi/vminpoly

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