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

Aligning the page content in perfect harmony with the footer

I've encountered variations of this question in the past, but I haven't found a solution that fits my specific needs. My challenge involves having a footer fixed at the bottom of a page, even when the content doesn't fill the entire page. Ad ...

Enhance the appearance of your image by adding a stylish frame or border without altering its

Is there a way to add a frame to an image without causing it to shrink due to borders? Below is the code I have tried using: .img-border { height: 100%; width: 100%; position: absolute; z-index: 1; } <div class="border border-black i ...

Using @font-face with Rails version 2.3.8

Hello, I am having trouble including a custom font in my Rails application. I am currently using Rails 2.3.8. I have placed my font folder in the public folder and below is my CSS code. However, it seems to not be working. Can anyone provide some assistan ...

Is there a way to increase the values of my dropdown menu options by selecting a different option in another dropdown menu?

I have a pair of select boxes: <select class="years"> <option value="1">1 year</option> <option value="5">5 years</option> </select> <select class="factor"> <option value="1">normal</option> & ...

Show concealed elements above everything else

I've encountered an issue with my custom dropdown list as it displaces other elements when it appears. I want it to overlay on top of everything else, similar to the default select behavior. Despite trying to set position: relative; and z-index:100;, ...

What is the best way to transmit data as a reply from a Node.js server to an AJAX client?

Currently, I am utilizing a function to transmit data regarding an HTML element as an object: function postItem(input) { $.ajax({ type: "POST", url: "http://localhost:8080", data: input, success: function(message) { Hconsole.log(&a ...

Enhancing highcharts gauge with dynamic data from JSON

I've been working hard to get my Gauge looking just right, and now I'm attempting to update it with JSON data from Thingspeak. However, when I check the page, I keep running into a ReferenceError - it says "data is not defined." If you want to t ...

How can Node.js and Socket.io be used with either PHP or jQuery to search within a text file?

I currently have a setup where I am using node and socket io to transmit a dynamic time format (HH:MM:SS) to my apache-served index.php file. I have successfully implemented the functionality to display the time in the PHP file. Now, my goal is to dynamic ...

Ensure your mobile site is optimized for full width display

Imagine a webpage with a fixed width of 1280px. Is there a way to instruct a smartphone to automatically scale this page to full width upon loading? Currently, I am using: <meta name="viewport" content="width=1280, initial-scale=1"> However, it d ...

What is the best way to display jQuery/AJAX response in a table cell?

I am struggling with a script that retrieves data from a SQL database query and need help placing the result in a specific table cell. Here is the query: <script type="text/javascript"> $(document).ready(function(){ $('.typeval').change(f ...

Deselect the checkbox using jQuery

How can I retrieve the value of an unselected checkbox (id) after it has been deselected? For example, when I select checkbox 1, I get a value of 1. But when I deselect checkbox 1, the value remains the same (1). Does anyone know how to solve this issue? ...

Craft a Unique Responsive Background Design

I'm eager to create a background like this, but I'm struggling to figure out the best approach. My attempt with transform: skewY(-6deg) ended up skewing my entire page instead of just the background. Could someone please assist me in finding th ...

Troubleshooting CSS rendering issues on Chrome browser

Currently in the process of developing a new website based on an old template. The site appears as intended in IE, Safari, and Firefox, but for some reason Chrome is not rendering any of the css. Just to clarify, none of the links are functioning at this ...

Activate Select2 dropdown when text input is in focus

I am facing an issue with a form that has one text input and one select2 element (Version 4.0.0). My goal is to have the select2 element open when the text input is focused. Here’s what I have attempted : <select list="userAccountsMap.values" listKe ...

The div is empty when trying to display Google Maps

When I set the height of my Google map div in pixels, it displays correctly. However, when I try to set it as a percentage, specifically 100%, the map does not show up. I have tried setting the height of all parent divs as well, based on suggestions from S ...

Combine all div elements to create a unified image and then proceed to save it as a jpg file before uploading to the server

These are the divs below: <div style="width:800px; height:420px; position:absolute; top:0px; left:0px; z-index:10; background-image: url('https://3t27ch3qjjn74dw66o1as187-wpengine.netdna-ssl.com/wp-content/uploads/2016/05/052516-800x420-vege-Wallp ...

Navigation website with a twist

My design features a main navigation that is rotated 90 degrees, while the sub-menu remains horizontally aligned. <div id="nav"> <ul> <li><a href="#">Woonaccessoires</a></li> ...

Activate the Twitter Bootstrap Lightbox when the page is loaded

Is there a way to make my twitter bootstrap lightbox automatically trigger when the HTML page loads? Currently, I have this script in my 'main.js' file: function lightbox(){ $('#myLightbox').lightbox(); }; I heard that I can us ...

Personalized Bootstrap 4 navigation bar tailored specifically for the application process

Seeking a customized progress nav-bar for my application, with a design similar to this: https://i.sstatic.net/ahDBa.png Discovered it on this website. Despite using the provided HTML and CSS, I'm unable to make it work with Bootstrap 4. HTML < ...

Is there a way to attach a CSS class to a BoundField in order to locate it using jQuery?

I need to assign a specific class name to certain BoundFields within the GridView control. This way, after the GridView has been populated with data and displayed, I would like to have something similar to the following: <td class="Tag1">Some data c ...