1

I have a website containing a large square (same height as width).

I would like the square to always have 95% of the browser window height as its height. But I don't want to actually change the defined height/width of the square. I would like to use the CSS zoom property. If I change the browser window to a small size, it should zoom out so that the square is still fully visible.

Matt Coughlin
  • 18,666
  • 3
  • 46
  • 59
Chris
  • 6,093
  • 11
  • 42
  • 55
  • Note: `zoom` is non-validating CSS that's not supported on Firefox and Opera. For a cross-browser zoom solution, see [CSS zoom property](http://stackoverflow.com/q/3117699/1306809) and [complete styles for cross browser CSS zoom](http://stackoverflow.com/q/13393588/1306809). – Matt Coughlin Mar 15 '13 at 17:28
  • After thinking about the question more, I realized that I may have answered the question incorrectly. The initial demo I made zooms the square, not the entire page. If you need to zoom the entire page, see the second demo added to the answer below. To be clear, which do you need to zoom, the entire page or just the square? – Matt Coughlin Mar 16 '13 at 02:33

1 Answers1

7

Here's a starting point (with cross-browser support added for Firefox and Opera): JSFiddle Demo

HTML

<div class="square"></div>

CSS

html, body {
    margin: 0;
    height: 100%;
}
.square {
    width: 300px;
    height: 300px;
    margin: 0 auto;
    background-color: #7ad;
    -moz-transform-origin: center top;
      -o-transform-origin: center top;
}

jQuery

function zoomSquare() {
    var $square = $('.square');

    var viewportHeight = $(window).height();
    var squareHeight = $square.height();
    var desiredHeight = Math.round(viewportHeight * 0.95);
    var zoom = (desiredHeight / squareHeight);

    $square.css('zoom', zoom);
    $square.css('-moz-transform', 'scale(' + zoom + ')');
    $square.css(  '-o-transform', 'scale(' + zoom + ')');
}

// When the browser is resized
$(window).on('resize', function(){ zoomSquare(); });

// When the page first loads
$(document).ready(function(){
    zoomSquare();
});

Update:

The above code zooms the square element, rather than the entire page. If the entire page needs to be zoomed (which may be the case if there's other content on the page outside of the square), try this second JSFiddle Demo.

When zooming the entire page, I found that zooming in causes horizontal scroll bars to appear in all browsers, which is very bad for usability. To avoid this, zoom out on small browser windows but do not zoom in on large ones. This is how the second Demo behaves (it will only zoom when the browser is very small).

Matt Coughlin
  • 18,666
  • 3
  • 46
  • 59