What is the best way to dynamically resize the content inside a div element based on its dimensions using

My challenge is to create a centered div on the page that resizes with the viewport while maintaining an aspect ratio of 16:9. However, I also need the font and content inside the div to scale proportionally as it resizes. Using vmin works well in most cases, but it would be perfect if the aspect ratio was 1:1 instead. Unfortunately, vmin checks for the lesser value between height and width of the viewport directly, and custom aspect ratios are not supported.

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-color:white;
}
.wrapper {
  width: 95vw;
  height: calc(95vw * 9/16);
  max-height: 95vh;
  max-width: calc(95vh * 16/9);
  background: center;
  background-color: blue;
  background-size:contain;
  margin: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
#lorem {
  color: aqua;
  font-size:10vmin;
  text-align:center;
  position:absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  margin:auto;
}
</style>
</head>
<body>
<div class="wrapper">
  <p id="lorem">
    This text should scale with div only.
  </p>
</div>
</body>
</html>

https://jsfiddle.net/Addictorator/70fq44sv/2/

If you resize the window vertically, you'll see the issue I'm trying to solve.

I'm exploring options to achieve this effect using pure CSS, although I suspect JavaScript might be necessary. One approach could involve scaling each element separately based on the ratio of the original or previous div size compared to the current size. Alternatively, a JavaScript solution could replicate vmin behavior but factor in the 16:9 aspect ratio instead of 1:1. Ideally, I'd prefer a pure JS solution without jQuery. While I've attempted to tackle this myself, my JavaScript skills are quite basic.

Thank you for any help or suggestions you can provide!

Answer №1

For a demonstration of the solution, please refer to the CodePen example here.

The implementation is straightforward. Upon window resize, we retrieve the clientHeight of the parent element and calculate an integer value suitable for setting as the font-size of the p element.

This approach should effectively address your issue.

// Setting font-size on document ready
document.onreadystatechange = () => {
  if (document.readyState === 'complete') {
    var wrapperHeight = document.getElementById('wrapper').clientHeight;
    var relativeFontSize = wrapperHeight / 10 + 'px'; // Adjust divisor for desired font size
    document.getElementById("lorem").style.fontSize = relativeFontSize;
  }
};
// Handle window resize event
window.onresize = function(event) {
  var wrapperHeight = document.getElementById('wrapper').clientHeight;
  var relativeFontSize = wrapperHeight / 10 + 'px'; // Adjust divisor for desired font size
  document.getElementById("lorem").style.fontSize = relativeFontSize;
};
body {
  background-color: white;
}
#wrapper {
  width: 95vw;
  height: calc(95vw * 9/16);
  max-height: 95vh;
  max-width: calc(95vh * 16/9);
  background: center;
  background-color: blue;
  background-size: contain;
  margin: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  font-size:60px;
}
#lorem {
  color: aqua;
  text-align: center;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  margin: auto; 
}
<div id="wrapper">
  <p id="lorem">
    This text should scale with the div only.
  </p>
</div>

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

extracting information from an external document

I'm quite new to both three.js and JavaScript, so please bear with me if this is a simple question. I have a JSON file with a list of objects containing data like this: [ { "x":x,"y":y,"z":z ,"r":r}, { "x":x2,"y":y2,"z":z2 ,"r":r2}, { "x":x3,"y":y3, ...

I am encountering an error message that states "Uncaught TypeError: Cannot read property 'use' of undefined."

https://i.sstatic.net/HcwYr.png Error: Unable to access the 'use' property of an undefined object ...

Techniques for eliminating single quotes from string arrays and then creating a new array by separating them with commas

I have an array of elements containing IP addresses with single quotes. I need to remove the single quotes and separate each IP address into new values, storing them as strings in another array using JavaScript. let myArray = [ '10.202.10.800,10.202 ...

Steps to resolve the issue: The 'jsx' functionality is not activated at the moment

I recently started working with ReactJS and I came across a similar error message in this post: Syntax Error: Support for the experimental syntax 'jsx' isn't currently enabled. Despite reading it, I am still unable to solve my issue. When I ...

Is it possible to asynchronously access a JSON object that has been retrieved from a local file on a global scale using the XMLHttpRequest method and

Having some trouble manipulating data from a local JSON file using this technique (no jQuery) as I can't seem to access the object on a global scale: var actual_JSON; function loadJSON(callback) { var xobj = new XMLHttpRequest(); xobj.o ...

Bandcamp API sales data retrieval feature

Looking for assistance with a call to the Bandcamp API. Every time I request /http://bandcamp.com/api/sales/1/sales_report/, I receive this message in the response: /"error_message":"JSON parse error: 757: unexpected token at ''/ ...

Replace Font Awesome icon with a background image

Looking to replace a Font Awesome icon with a background image using only CSS. Current Setup: https://i.sstatic.net/tkPXz.jpg .btn.btn-default.bootstrap-touchspin-up:before { font-family: Fontawesome; content: "\f067"; font-size: 14px; } ...

Tips for setting up a popup menu when clicking a button on a webpage

I am currently working on developing a popup menu with a greyed-out background that appears when the user clicks on a button in React. My code implementation is as follows: // The ifButtonClicked function is called when another button is clicked // Some ...

There appears to be an issue with the functionality of the JavaScript calculation function

Check out this JS Fiddle. I've tried my best in writing the script, but it just doesn't seem to work properly. If you could spare some time to review it and provide feedback on what I might be missing or doing wrong, I would greatly appreciate it ...

What are the methods for choosing various boxes using the UP/DOWN/RIGHT/LEFT arrow keys?

This code snippet displays a 3x3 matrix where boxes can be hovered over and selected. The goal is to navigate around with keys and select boxes using ENTER. Can anyone provide guidance on how to achieve this functionality? <link rel="stylesheet" href ...

Automatically resizing textures in Three.JS with WebGL

Seeking assistance to overcome a challenge :) I am using Three.JS to showcase high-resolution equirectangular images on a sphere (20000x10000 pixels). Image quality is crucial for my web application, and bandwidth is not a concern. My issue is that ThreeJ ...

My function seems to be functioning perfectly fine in Angular and Express, but for some reason, it's not working in Parse Cloud Code. What could

I am facing an issue with my code where it seems to be stuck. After testing it in both Angular and Express, I realized that the code is only progressing up to a certain point due to the requirement of the Master Key to edit the User table with new data. ...

Can a JavaScript callback be transmitted via JSON?

Is there a way to pass a callback function via JSON instead of using a function object? window.onpopstate = function(e) { var state = e.state; switch(state['method']) { case 'updateFields': updateFields(sta ...

Implementing an autosuggest feature for the TagsInput component

When developing my website, I utilized JavaScript, the React framework, and a library called mui. One of the user input features on my site is powered by TagsInput, allowing users to input data, press enter, view the tag, and optionally delete it. Unlike ...

Identifying added elements that respond to link hover effects

I've been working on a project where I'm trying to replace the default browser cursor with an SVG one using jQuery. Everything seems to be working smoothly, except for changing the cursor when it hovers over links - nothing I've tried so far ...

jQuery TextExt - Trouble with setting the URL for Ajax autocomplete

Currently, I am utilizing the jQuery TextExt plugin for autocomplete. While using its example json url (data.json), everything functions as expected without any issues. However, when attempting to use my own custom url, similar to the one below: $('# ...

Organize the rows of the table based on two variables

Currently, I am tackling the challenge of dynamically sorting a table using javascript/jQuery. The table rows come with two crucial attributes: deadline (measured in Unix timestamp) status (either 1 or 2) The primary requirement is to sort the table by s ...

Delivering static frontend JavaScript file using ExpressJS

Hey there, I'm running into a bit of trouble when trying to load the frontend JS file on my Express server. Here's how my file structure looks: https://i.sstatic.net/EHDSp.png Here's my Server Code - app.set("view engine", " ...

The progress bar in Java Script is static and cannot be customized to change colors

Trying to use HTML for image uploads and I've created Java code to monitor the progress of the upload. However, I'm facing an issue where I cannot change the color of the progress loading bar. Below is the code I am currently using for uploading ...

Woops! Looks like there's an issue - the property 'url' is not defined and cannot be

I am currently working on fetching data from a REST API using angular2, and everything seems to be going smoothly. However, I have encountered an error that only appears in the console when calling {{content.img.url}}. Interestingly, the code executes fine ...