Preserving proportions in CSS using both width and height measurements

My objective is to set an aspect ratio (for example, 4:3) for a DIV and all its children with the styles WIDTH:100% and HEIGHT:100%. Initially, this method works well by setting the parent's

WIDTH:100%

and then adding

PADDING-BOTTOM: 75%; // (3/4)*100

to the first child element. However, when I maximize the window on a 1080p monitor, the inner box will correctly expand to 100% width and 75% of the width in height, resulting in a 1920x1440 resolution. As a result, scrollbars are required to view the complete content within the div.

I would prefer the inner box to be equivalent to (window.innerHeight / 3) * 4 in width with black bars on either side. To achieve this, I tried setting the height on the parent and adding padding-right to the child, expecting black bars on the right instead of the bottom, but unfortunately, it didn't work as expected.

In an ideal scenario, I want my div to maintain a 4:3 aspect ratio regardless of the parent's dimensions, with black bars if necessary, without exceeding the parent's size and causing scrollbars. Can this be achieved solely with CSS, or will JavaScript be required?

Edit:

Using

<div style="width:133vmin;height:100vmin;margin-left:-66vmin;left:50%;background: #f00; overflow:hidden;">

I managed to create a div with a 4:3 aspect ratio and black bars on the sides. However, if the height is insufficient, the div does not resize accordingly. It seems that I need to combine both approaches for a comprehensive solution.

Answer №1

My attempt at a solution unfortunately does not function correctly with the most recent stable version of Chrome. A bug has been reported and can be viewed here:

On the bright side, it is compatible with Firefox 25.0 and Chrome Canary 36.0.1922.0

<html>
<style>

body {
    margin:0;
    background: #000;
}

#block1 {
    display: inline-block;
    position: relative;
    width: 100vw;
    max-width: calc(100vh * 1.33333); // (4 / 3)
}
#block1:after {
    content: '';
    display: block;
    margin-top: 75%; // (3 / 4) * 100
}
#block2 {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: red;
}

</style>
<body>
<div id="block1"><div id="block2"></div></div>
</body>
</html>

Answer №2

Here is the CSS code you need:

#container{
    position: relative;
    width: 100%;        /* set desired width */
}
#container:before{
    content: "";
    display: block;
    padding-top: 75%;   /* initial ratio of 1:1*/
}
#content{
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}

This solution works across all browsers, even back to IE8.

You can find more information in this informative article:

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

To extract three records from storage and store them in the dbResult using a promise join technique

How can I efficiently retrieve and store 3 records in dbResult using promise join? Currently, I have code that retrieves a single record as shown below: req.oracleMobile.storage.getById(registry.getIncidentPhotoStorageName(), incident_id + '_01&apos ...

"Enhance your website with the powerful autocompletion feature of

I am using Zend Framework to create a form element that utilizes Zend_Dojo_Form_Element_ComboBox. By setting dojox.data.QueryReadStore as the store type, I am able to generate a list of selectable values in my HTML input field. This allows me to either cho ...

Determining the Similarity of jQuery Selectors' Selected Elements

I'm looking for a way to programmatically identify if two jQuery selectors have chosen the exact same element. My goal is to iterate over multiple divs and exclude one of them. This is what I envision: var $rows, $row, $row_to_exclude; $rows ...

Both the "if" and "else if" conditions are performed within the filter function in Angular-8 using JavaScript

When running the code snippet below, both the "if" and "else if" conditions are executed within the filter function. However, the output I am receiving is not as expected: https://i.sstatic.net/WpFy5.png this.users.filter((hero)=> { if(hero.name ...

Update the default arrow icon in the expand/collapse navigation bar

I need help changing the downward arrow in the code below to a fontawesome icon. I'm unsure about how to: 1. Remove the default arrow on the right of the parent node. 2. Use "+/-" symbols to represent the collapse state. It seems that the onclick c ...

Discovering a client's computer setup through a website

Is it possible to retrieve the hardware configuration of a client's PC from a website? I am working on developing a website that displays local system configurations. I am aware that there are numerous tools available for this purpose, but the client ...

Typescript is failing to compile classes in a reliable sequential order

In my MVC 5 project, I am using TypeScript and angular. There are three TS files: Controller1.ts, Controller2.ts, and app.ts. The issue arises when I compile the program for the first time - everything usually compiles correctly in the expected order. Howe ...

When I press the play button, the sound doesn't start playing

This is my script in action: <script> var audioObj = document.createElement("audio"); document.body.appendChild(audioObj); audioObj.src = "http://example.com/audios/Kalimba.mp3"; audioObj.load(); audioObj.volume = 0.3; audioO ...

Is there a problem with textbox support for multi-line strings?

I'm having trouble getting a textbox to display multiple lines of text. For instance, when I copy three lines of text from Microsoft Word and paste it into the textbox, only the first line appears. The other two lines are not showing up, and I'm ...

The bond between TypeORM and express

I am working on establishing Many-to-One and One-to-Many relationships using TypeORM and MySQL with Express. The database consists of two tables: post and user. Each user can have multiple posts, while each post belongs to only one user. I want to utilize ...

Reading uploaded .PDF or .DOC files as images without the need for conversion

Lately, I've been brainstorming a new feature where users can upload files such as .pdf or .doc and have them displayed as images on the webpage. I'm curious if there's a way to achieve this without converting them to .jpg or .png using thir ...

Unable to locate and interact with element using CSS Selector in the webdriver

I am having trouble locating the element that contains both "Confirm" and "Cancel" without using Xpath. Can anyone suggest a better approach to find this element? Below is the HTML code snippet: <div class="ui-dialog-buttonpane ui-widget-content ui- ...

Conceal player controls for HTML videos on iOS devices

How can I hide the video player controls in Windows and Android, they are hidden but still visible on iOS. I have tried different methods but can't seem to hide them. Here is what it looks like on iOS: https://i.sstatic.net/Uwrg3.png Here is my code ...

AngularJS - Finding the position of an element with the query "is located at the bottom of the page"

How can we effectively determine if there is more content to be scrolled in Angular, especially when dealing with a single-page app with a fixed bottom navbar? I am looking for a way to visually signal to users that there is additional content available b ...

Display the ViewModel in the view once the ajax call has been made

When I make an AJAX call to invoke an action, pass my ViewModel to it, and then attempt to open a new view with a different ViewModel, the redirectToAction and return view methods are not functioning as expected. Other solutions I have come across only inv ...

Aligning an object in ThreeJS to always face the camera, ensuring it is perfectly straight and flat

Reviewing this demo http://codepen.io/anon/pen/JdmMPW, I am working on creating a camera orbiting around a sphere with text labels/satellites (represented by the plane object) that should always face the camera. function render() { marker.lookAt(camera.p ...

Transforming html designs into pdf files using wkhtmltopdf tool

While attempting to convert three HTML files (body template, header template, footer template) to PDF using wkhtmltopdf, I encountered an error stating "Unknown long argument --header-htmlá". This issue arose after a recent PC update, as everything was fu ...

Encountering an issue where I am unable to access properties of undefined (specifically 'up') within Material UI styling

I encountered an error message Uncaught TypeError: Cannot read properties of undefined (reading 'up') while executing the code snippet below: I am having trouble with compiling my react js Code Snippet from Index.js import React from 'react ...

Why does my ajax request show the result in the php file rather than redirecting to the html page?

I've developed a series of AJAX functions that retrieve data from a PHP file. However, one of the functions redirects to the PHP file to fetch data but fails to return to the HTML page for data insertion. Here is the code used to fetch a table from a ...

What is the process for transferring selections between two select elements in aurelia?

I am attempting to transfer certain choices from select1 to select2 when a button is clicked. Below is my HTML code: <p> <select id="select1" size="10" style="width: 25%" multiple> <option value="purple">Purple</option> &l ...