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

Displaying a particular form depending on user selection in PHP

Being new to the world of HTML and PHP, I have a question. In my HTML code, there is a form with two options to select from: lesson or topic. I want to display a different form depending on whether the user selects "lesson" or "topic." How can I achieve ...

What is the process for eliminating an attribute using adblock?

Is it possible to eliminate specific attributes with an ad blocker on a webpage? I am specifically interested in removing the title attribute, as shown in this example: <p title="Free Web tutorials">W3Schools.com</p> After applying the ad blo ...

Generate an adjustable grid layout (with rows and columns) to display information retrieved from an API request

I have recently started learning React JS and JavaScript. To practice, I am working on a small project where I am facing an issue with creating dynamic rows and columns. My aim is to display data in 4 columns initially and then move to a new row and column ...

Customizing hover color with tailwind CSS

How can I change the color of an icon on mouseover using Tailwind CSS? I have tried to go from this https://i.sstatic.net/ObW6C.png to this https://i.sstatic.net/Tagp3.png, but it's not working. .btn { @apply agt-h-10 agt-w-10 agt-bg-zinc-100 agt- ...

Ways to obtain data in JavaScript function from HTML

Struggling to pass the key from a database query in HTML using PHP to a JavaScript function? You're not alone. The challenge lies in passing the field_id to the updateRecords() JS function through the onClick() event of an HTML button. Previously, se ...

What is the process for creating a modal transition?

I am attempting to add animation to a modal using a transition effect. My goal is to open it slowly, either from the center of the screen or from the bottom. However, I am struggling to understand how this can be achieved... While searching on Google, I c ...

Attempting to create a button that will only appear for items with a defined value for a specific variable

I am currently facing an issue with a template that needs proper population. The store locator on my website lists pharmacies and displays their relevant information (phone number, address, hours of operation) along with three buttons (view store, view fl ...

How to implement Thymeleaf's notConnected tag when using Spring Social

After transitioning my JSP views to HTML Thymeleaf views, I encountered a problem. In my old JSP views, I used a social:notConnected tag. However, it seems to have been removed and the only one available is social:connected as shown below. <div id="co ...

Load information from a JavaScript object when the user clicks dynamically

My challenge involves utilizing a JavaScript object that contains video information such as title and source URL. Within my HTML, I have image placeholders and the goal is to trigger a modal pop-up (using Twitter Bootstrap modal) of the specific video when ...

Having trouble implementing a nested grid system in Bootstrap

Struggling with creating a grid layout that looks like the one in this image. I initially thought of setting up a row with 2 divided columns, then adding another row+column within each of those 2 columns to place a card inside. This is an excerpt of my c ...

Flexbox margins (exceeding 100% total width)

Currently collaborating with @c4rlosls and we are facing 2 issues: https://i.sstatic.net/44WcI.jpg If the parent container with class container-fluid has a px-0, it extends beyond 100% width. Additionally, the elements with classes .cont2 a and .cont3 a do ...

Update the html() function to include any content that has been typed into a

I have a webpage structured like this: <div id="report_content"> Some information <textarea name="personal"></textarea> <b>Other information</b> <textarea name="work"></textarea> </div> Whe ...

Designing the autocomplete dropdown feature in Bootstrap UI

I'm currently developing an app that is utilizing AngularJS and Bootstrap, with the assistance of Bootstrap UI. Specifically, I am working on implementing the typeahead feature. However, I am facing a challenge in trying to ensure that the dropdown li ...

Assigning a height of 100% to a div element results in the appearance of

In a div within the body, there are only 3 lines of text. The background color was only filling up to those 3 lines of text. To make the color fill up the entire vertical space of the browser, I adjusted the CSS height properties of html & body to be ...

What is the best way to center this menu on the web page?

Is there a way to center this menu on the web page for better alignment? Any suggestions on improving the code are welcome. Thank you in advance. Edit: Also, how can I modify the hover effect to change the background color to green and make it expand full ...

Ways to prevent a background image from repeating in an HTML email without relying on CSS

I created a custom background picture, but when I tried to use it with CSS in Outlook, it didn't work. So, I added the picture directly into the body tag which allowed me to display it, but now it is repeating. Even after trying to prevent the repeti ...

Looking to integrate the date, month, and year selection tags into the inline format

The Edit User Profile page includes a Birthday field, which is currently displayed vertically. I am looking to change the layout so that the Birthday field appears horizontally. Here is the code I am using: Within visitors/edit.html.erb, <%= simple_f ...

Small hiccup in jQuery leading to duplicate entries in the field

I am attempting to use jQuery to add the value of a select box to both a hidden input field and a div that is displayed in public view. Below is the code I have: <script type='text/javascript'> $("#departments_submit").click(function(){ ...

Creating a handshake process for hybi-17

I am currently in the process of creating the handshake for the websocket hybi-17 protocol. I have been referencing the draft available at . Based on the guidelines provided in the draft, I have developed the following code snippets for both the client (us ...

Creating a carousel similar to the one on Skipperlimited's website can be achieved

I am working on a project and I would like to create a design similar to the one found at Specifically, I am interested in replicating the carousel of images and the rotating carousel within their logo. Can anyone provide guidance or suggestions on how to ...