Maintain correct aspect ratio when zooming in the body

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>

Answer №1

Once the width surpasses 960px, all if-else conditions become invalid, ceasing the scaling process.

To observe this in action, feel free to replicate it in your browser console. I've included a specific case for exceeding the 960px threshold.

function adjustPage() {
  console.log("ratio: " + ratio);
  console.log("appwidth: " + appWidth);
  console.log("curwidth: " + currentWidth);
  console.log("curheight: " + currentHeight);
  console.log("appheight: " + appHeight);
  currentWidth = window.innerWidth;
  currentHeight = window.innerHeight;

  if (appWidth > currentWidth && appHeight > currentHeight) {
      console.log('both dimensions exceeded');
      ratio = currentWidth / appWidth;
      app.css('zoom', ratio);
  } else if (appWidth > currentWidth) {
      console.log('only width exceeded');
      ratio = currentWidth / appWidth;
      app.css('zoom', ratio);
  } else if (appHeight > currentHeight) {
      console.log('only height exceeded');
      ratio = currentHeight / appHeight;
      app.css('zoom', ratio);
  } else if (appWidth < currentWidth) {
      ratio = currentWidth / appWidth;
      app.css('zoom', ratio);
      console.log('smaller width case');
  }

}

Answer №2

Uncertain, however, if you focus solely on the width of the window and maintain a body with the same height/width ratio, CSS can assist:

(height may overflow html)

html {
  background-color: red;
  position:relative;
  padding-top:56.25%;/* 54/96=0.5625 */
}
body {
  background-color: gray;
  position:absolute;
  top:0;
  bottom:0;
  left:0;
  right:0;
}
<h1>Test App</h1>

To comprehend how this functions, refer to:

https://www.w3.org/TR/CSS2/box.html#padding-properties

<percentage>

The percentage is calculated in relation to the width of the generated box's containing block, even for 'padding-top' and 'padding-bottom'. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1.

You can also prevent the box from exceeding the window's height:

(box will not overflow the window)

html {
  background:tomato;
  margin:0;
  max-width:156vh;
  position:relative;
  margin: 5vh auto;
}
html:before {
  content:'';
  padding-top:56.25%;
  display:inline-block
}
body {
  position:absolute;
  top:0;
  left:0;
  bottom:0;
  right:0;
  background:#aaa;
  /* makeup*/
  display:flex;
  align-items:center;
  justify-content:center;
  color:white;
  font-size:10vh;
}
keep my ratio & inside window

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining an AJAX POST within a JSON GET request

function performTest() { $.getJSON("/Home/GetAp", function (result) { $.each(result, function () { if (this.is_disabled == "False") { var a = $("#MainDiv") .append('<div id="imagew ...

Conceal an element within the initial row of the table

Below is the table structure: <table id="mytable"> <tr> <td>name</td> <td> <a id="button1" class="button">link</a> </td> </tr> <tr> <td>name2</td> ...

Maintain the height of the image equal to the height of the

I've been facing challenges with adjusting the height of this image to match the div container. I've experimented with various height properties such as max-height, min-height, normal height, auto, and 100%, but none seem to be providing the desi ...

displaying the download status of a file during the download process with PHP and jquery

Exploring the creation of a unique download manager with PHP and jQuery. In search of a script that enables file downloads with visible progress tracking. The attempted implementation has not yielded the desired results: jQuery function init ...

Initially, the 'display none' CSS command may not take effect the first time it is used

I am currently working on a slideshow application using jquery.transit. My goal is to hide a photo after its display animation by setting the properties of display, transform, and translate to 'none' value. Although the slideshow application work ...

How can I create a webpage that is fully responsive to both width and height, with text that automatically scales to fit the

I am currently using Bootstrap and Angular to develop a single-screen webpage tailored for small screens such as the Adafruit 2.2" or 2.8" screen for the Raspberry Pi, or mobile phone displays. I aim to make all content (specifically about 3-4 rows of a ta ...

What could be causing me to receive two responses from this AJAX request?

Can someone shed light on why I am receiving a double success response from this AJAX call using Bootstrap modals? Instead of getting test, I am seeing testtest. After inspecting the console, it appears that only one request is being made and I've c ...

Picking a variety of elements and determining their heights using the height

I'm curious why this jQuery code isn't working as expected: hdr = $('.header-wrapper, #top-bar, #new-showroom-header').height(); My intention is to retrieve the heights of multiple elements and store them in a variable. I assumed that ...

Interactive rotating display with constantly updating information

Recently I started learning angularJS and I must say, I am already hooked. I have developed a website that pulls data from JSON files (created by external scripts) locally to show real-time information on various pages. Now, I want to include a sliding car ...

using an SVG mask declared in HTML to apply masking

I've been experimenting with masking using an SVG shape that I created in the HTML content. I've tried various options: mask, -webkit-mask mask-image, -webkit-mask-image different MaskUnits and MaskContentUnits mask-type: luminance or not Desp ...

Having trouble with jQuery animate function?

I have been struggling to get my animate function to work, despite looking at multiple similar posts and making modifications to my code. My goal is to make an image of a plane move from left to right across the screen and stop halfway. Here is the code I ...

Tips on utilizing jQuery or JavaScript to efficiently filter out outcomes exceeding a specified range

<input type="range" name="rangeInput" min="100000" max="750000" onchange="updateTextInput(this.value);"> Displayed above is the slider code that provides a value output below. <div id="sliderValue"> <p>Max Value £</p> <input t ...

Trouble with text box focus functionality

Can someone help me focus a text box using code? Here is the code snippet: <input></input> <div id="click">Click</div> $(document).ready(function(){ $("#click").live("click", function() { var inputBox = $(this).prev(); $( ...

Interactive sidebar scrolling feature linked with the main content area

I am working with a layout that uses flexboxes for structure. Both the fixed sidebar and main container have scroll functionality. However, I have encountered an issue where scrolling in the sidebar causes the scroll in the main container to activate whe ...

Issue showing hidden content that was loaded using ajax

I'm currently working on a personal project where I am using ajax and jQuery to load elements onto a page. However, I am facing an issue with displaying specific elements under certain conditions after they have been appended to the DOM. There are ce ...

Error message in JS and HTML is totally bizarre

My expertise in JavaScript is very limited, so the terms I use might not be entirely accurate. However, I'll do my best to explain the issue at hand. I'm facing a peculiar problem... I've been attempting to modify someone else's JS scr ...

Unable to invoke the jQuery function within CakePHP3

I am having trouble calling the jQuery function mentioned below in my CakePHP3 MVC project. There are no error messages, but nothing seems to be happening. The code is set up so that jQuery gets included automatically. The function I am trying to call sh ...

Continuously invoking a function until jQuery's .post method has completed loading

As I am diving into the world of jQuery framework, I encountered a situation where I used the readyState() function while working with AJAX in regular JavaScript to display a loading gif image. However, when transitioning to using jQuery's .post() met ...

Changing the display of elements using Javascript in IE6 by modifying class

Currently, I am facing an issue at work that involves a piece of code. The code functions correctly in Firefox 3.6 where clicking on a row changes its class name and should also change the properties of the child elements. However, in IE6 and possibly othe ...

Prevent rapid flashing by adding a delay to the spinner in the jQuery Validations plugin

I'm currently utilizing the jQuery validation plugin available at http://docs.jquery.com/Plugins/validation for implementing client-side validations. For a remote validation to verify the availability of a username in the database, I intend to prolon ...