Maintain the div's aspect ratio by adjusting its width according to its height

I am seeking a way to maintain the width of the .center div in relation to its height, following a 4:3 aspect ratio (4 units wide for every 3 units high). The height of the div should be set to 100%, and I also need to align the div horizontally at the center.

You can observe this effect on a website with a flash application, such as this one.

This is the current setup:

HTML:

<div id="stuff" class="center" width="800" height="600"> 
     <canvas id="someHTML5">You cant play HTML5</canvas>
</div>

CSS:

.center {
    position: absolute;
    left: 50%;
    width: 800px; /* I want to make this relative; ideally, it would be width: height/3*4 */
    height: 100%;
    margin-left: -400px; /* Adjusted for horizontal alignment */
    z-index: 100;  
}

In addition to the CSS styling, there is JavaScript code running to handle dynamic updates on the client side.

Answer №1

If you want to adjust the width of a box relative to its height, consider utilizing the vh unit as a viewport relative length for the width property.

The Viewport Relative Length Spec mentions that these lengths are based on the initial containing block, scaling accordingly when the block size changes.

.center {
    position: absolute;
    left: 50%;
    width: 133.33vh; /* 100 * 4/3 ratio */
    height: 100%;
    margin-left: -66.66vh; /* width / 2 */
    z-index: 100;
}

Check out the working demo here.

It's important to note that vh and vw viewport-percentage lengths are supported in IE9+.


Browser Compatibility Information

Credits: Mozilla Developer Network

Answer №2

I developed a custom script that enables video-like resizing for the content.

window.onresize = function() {
  resize();
};

function resize() {
  var wrapper = document.querySelector(".wrapper");
  var wrapperwidth = 1920;
  var wrapperheight = 1080;
  var vw = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
  var vh = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
  var ratio = Math.min(vw / wrapperwidth, vh / wrapperheight);
  wrapper.style.transform = `translate(-50%, -50%) scale(${ratio})`;
}

resize();
.wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 1919px;
  height: 1079px;
  overflow: hidden;
  background-color: red;
}

/* demo text (smiley face) */

.wrapper::after {
  content: ":)";
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 200px;
  font-family: "Roboto", 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
<div class="wrapper"></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

Implement a feature in JavaScript that highlights the current menu item

I'm currently developing a website at and have implemented a JavaScript feature to highlight the current menu item with an arrow. The issue I'm facing is that when users scroll through the page using the scrollbar instead of clicking on the men ...

Having issues with Json stringification and serializing arrays

Having an issue with Json when using serializeArray. An example of my HTML form: <form action="" method="post" name="myForm"> ID: <input type="text" name="id" /><br/> State (XX): <input type="text" name="state" /><br/> <p ...

Looking to show an image when a checkbox is ticked and hide it when it is unticked in HTML?

How do I make a specific image appear when a user clicks on a checkbox? I'm unsure if I should use jQuery, Ajax, or another method. What is the best approach for this task? Your assistance would be greatly appreciated. I have successfully created the ...

Restoring styles back to the default CSS settings

I am currently working on creating visualizations using D3, and one challenge that I have encountered is the need to define a lot of styles within my code instead of in my CSS where I would prefer them to be. This necessity arises mainly to support transi ...

Running a series of functions consecutively with JQUERY

Currently, I am facing an issue with using an ajax method .load to replace the content of a div. The library I am working with does not allow me to replace the content of a div as some functions continue to run in the background. To overcome this challeng ...

Using jQuery, you can create and add an element to the page when a user clicks

Currently, my webpage contains numerous anchor tags that link to various video files, along with a single div element: <a href="http://www.example.com/example-1.mkv" class="video">1</a> <a href="http://www.example.com/example-2.mkv" class=" ...

The function has exceeded the time limit of 60000 milliseconds. Please make sure that the callback is completed

Exploring the capabilities of Cucumber with Protractor has been an intriguing journey for me. As I delved into creating a feature in Gherkin language, outlining the steps and scenarios necessary for my end-to-end tests, a new world of possibilities opened ...

Running the NPM build command results in an error specifically related to an HTML file

I encountered an issue in my AngularJS application when running the command: npm run build -- -prod The error message I received was: ERROR in ng:///home/directoryling/appname-play.component.html (173,41): The left-hand side of an arithmetic operation ...

A guide on showcasing the compilation results of PHP code directly on the web browser

How can I compile PHP code on an HTML Button click and display the compilation output in a browser? The code snippet below works well in the terminal but doesn't show anything in the browser. I am currently using XAMPP server on a Windows machine. &l ...

Vue.js: Issue with applying class binding while iterating over an object

I've been working with an object data that looks like this: object = { "2020092020-08-01":{ "value":"123", "id_number":"202009" }, "2020092020-09-01":{ "value& ...

Experiencing a lack of desired outcome in Outlook when using simple HTML with table elements

When creating a template for Outlook, I encountered an issue where the logo appeared on the right and the link text was on the left, which is the opposite of what I wanted. How can this be resolved? <center> <table width="600px;" style="margin:au ...

Automated logout feature will be enabled if no user interaction is detected, prompting a notification dialog box

Here is my working script that I found on this site. After a period of idle time, an alert message will pop up and direct the user to a specific page. However, instead of just the alert message, I would like to implement a dialog box where the user can ch ...

Craving assistance in coding permutations

Thank you for responding. I want to express my gratitude for your efforts in trying to assist me. Unfortunately, I have posted this problem on multiple websites and no one has been willing to help. Regarding my code, my objective is to count permutations. ...

"Keep a new tab open at all times, even when submitting a form in

I have a form with two submit buttons - one to open the page in a new tab (preview) and another for regular form submission (publish). The issues I am facing are: When I click the preview button to open in a new tab, if I then click the publish button a ...

Is it feasible for nested div to remain unaffected by bleeding when the container is positioned relatively and has an overflow hidden

Is it possible to bleed a nested div even when the container is positioned relative with hidden overflow? In this case, giving the nested div a fixed position is not an option. Please check out this unique example: http://jsfiddle.net/s7nhw/11/. If you ...

What is the best way to adjust a fixed-width table to completely fill the width of a smartphone browser?

In an ancient web application, the design was primarily constructed using rigid tables: <div class="main"> <table width="520" border="0" cellspacing="0" cellpadding="0"> <tr> <td>...</td> </ ...

Is it possible to achieve partial text stylization in Vue using Nuxt.js?

We're currently developing a Vue application Is there a way to style text partially, similar to this example? Although creating exact constraints from ellipses may not be possible, the functionality could still be achieved procedurally. ...

Unable to scroll when utilizing ng-html-bind functionality

My device specifications: $ ionic info Your system details: Cordova CLI: 6.2.0 Gulp version: CLI version 3.9.1 Gulp local: Ionic Framework Version: 1.2.4 Ionic CLI Version: 2.0.0 Ionic App Lib Version: 2.0.0-beta.20 OS: Distributor ID: LinuxMint Desc ...

Tips for displaying the message "{"POWER":"ON"}" within the else if statement (this.responseText == ({"POWER":"ON"})) {

Hey everyone, I'm trying to adjust the color of a button on my webpage based on the response I receive from this.responseText. I understand the JSON response, but for some reason, I can't seem to incorporate it into my code. If anyone could lend ...

what's causing the tabs in bootstrap to malfunction

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <link href="http://maxcdn.bootstrapcdn.com/bootst ...