I'm facing a challenge with my single-page web application that has fixed width and height. It doesn't scale properly to fit the page at all times.
Scaling based on its width works fine, but I want to achieve scaling from both width and height without stretching it, just fitting it correctly on the page with some extra spacing if needed.
The code below is as far as I've gotten, but it struggles to scale well when adjusting both width and height simultaneously.
var app = $('body');
var appWidth = app.width();
var appHeight = app.height();
var lastWidth = window.innerWidth;
var lastHeight = window.innerHeight;
var currentWidth;
var currentHeight;
var ratio;
app.css('zoom', ratio);
fitToPage();
$(window).resize(function() {
fitToPage();
});
function fitToPage() {
currentWidth = window.innerWidth;
currentHeight = window.innerHeight;
if (currentWidth !== lastWidth && currentHeight !== lastHeight) {
console.log('both width and height changed');
ratio = currentWidth / appWidth;
app.css('zoom', ratio);
lastWidth = window.innerWidth;
lastHeight = window.innerHeight;
}
else if (currentWidth !== lastWidth) {
console.log('width changed');
ratio = currentWidth / appWidth;
app.css('zoom', ratio);
lastWidth = window.innerWidth;
}
else if (currentHeight !== lastHeight) {
console.log('height changed');
ratio = currentHeight / appHeight;
app.css('zoom', ratio);
lastHeight = window.innerHeight;
}
}
html {
background-color: red;
}
body {
background-color: gray;
width: 960px;
height: 540px;
position:relative;
}
p{
position:absolute;
bottom:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<h1>This content shrinks once it's scaled</h1>
<img src="http://lorempixel.com/400/200/" />
<p>This shouldn't get cut off once it's scaled</p>
</body>