Tips for ensuring browsers maintain the aspect ratio specified by width and height HTML attributes when CSS is applied

I am seeking a method to reserve space in my layout for images before they are loaded by adding width and height properties to the img element.

This approach functions as anticipated:

img {
  display: block;
  border: 1px solid tomato;
}
<img src="" width="300" height="400" alt="">

However, when I attempt to limit the image size using max-width in my CSS, setting height: auto results in the collapse of the image's height:

img {
  display: block;
  border: 1px solid tomato;
  max-width: 200px;
  height: auto;
}
<img src="" width="300" height="400" alt="">

Is there a way to compel browsers to maintain the aspect ratio based on HTML attributes?


The issue persists. Both Firefox and Chrome now support internal mapping of width and height to aspect ratio, which fulfills my requirements.

One observation I have made is that the src attribute must be set for this functionality to work. Setting an image as fully loaded appears to reset the aspect ratio settings.

To accommodate lazy loading, a placeholder image can be used with the correct aspect ratio assigned to the src attribute.

Despite working well in Chrome and Firefox, I am still looking for a solution that also caters to older browsers and Safari (excluding IE).

Answer №1

To tackle this problem, I resorted to a clever workaround that may not be the most conventional solution.

The trick here is to enclose the image within an element whose height is calculated based on the maximum width of the image and its aspect ratio derived from the attributes.

There are a couple of things to note:

  • This method sets the height rather than the max-height, as images without a specified src lack intrinsic height despite having attributes.
  • If there are changes in the values of the height or width attributes, or in the max-width property in the CSS, then the style's height property must also be updated accordingly. This could mean a lot of manual adjustments, especially for multiple images.

It is possible to achieve this using JavaScript, but given the absence of that tag in your question, I chose to present a CSS-only approach.

I have included a small snippet of JavaScript that delays for 2 seconds before setting the image source to a dummy image with the provided dimensions. This demonstrates lack of distortion and mimics the effect of a slow-loading image.

setTimeout(() => document.querySelector('img').src = "https://dummyimage.com/300x400/000/fff.png", 2000);
img {
  display: block;
  border: 1px solid tomato;
  max-width: 200px;
  height: 100%;
}
<div class="img" style="height: calc((400/300)*200px)">
<img src="" width="300" height="400" alt="">
</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

The module 'myapp' with the dependency 'chart.js' could not be loaded due to an uncaught error: [$injector:modulerr]

Just starting out with Angular.JS and looking to create a chart using chart.js I've successfully installed chart.js with npm install angular-chart.js --save .state('index.dashboard', { url: "/dashboard", templateUrl ...

Displaying a collapsible table directly centered within the table header

I am having trouble centering my table header in the web browser page. When I click the "+" button, the data is displayed beneath the table header, but I want the collapsible table to be centered directly below the header. I have tried making changes in CS ...

Problem with sending a form using Ajax

I've set up a page that dynamically generates a list of items. Each item in the list includes a button to submit a form with data specific to that item (the sorting is working correctly). The form submission is handled by the following jQuery code: & ...

Dynamic sidebar that adheres to the content and is placed alongside it using JavaScript

I am in need of creating a sticky sidebar that will float beside my content column. The purpose of this sidebar is to contain jump links on the page, similar to what can be seen on this page, but with the navigation buttons positioned directly next to the ...

Tips for incorporating a personalized CSS stylesheet while utilizing Bootstrap

When trying to use my custom CSS alongside Bootstrap, I'm running into some issues. The !important tag doesn't seem to have any effect (I've also heard that using !important is not recommended). Additionally, using IDs instead of classes isn ...

How to divide an HTML string into an array using PHP

I am in need of some assistance from you all. The issue I am facing involves dealing with a string of HTML that looks like this: <h4>Some title here</h4> <p>Lorem ipsum dolor</p> (some other HTML here) <h4>Some other title ...

Using JavaScript to create CSS animations triggered on hover

Looking for a CSS Animation that will play forward once when the mouse enters a specific div, and then play in reverse when the mouse leaves. Check out my JsFiddle here. The div with the class ".item" should trigger the mouse enter event. The animation co ...

Ways to achieve a darker background with rgba(0,0,0,0.5)

Hey there, if this isn't the right place to post my query, could someone guide me on where to do so? TL;DR = I need to darken the background of my showcase image! I'm working on a website as part of an online course project to practice new skil ...

What is the best way to ensure that text fields remain hidden upon page load until the appropriate drop down option is chosen?

Is it possible to initially hide text fields and only reveal them when a specific drop down option is selected? The current JavaScript code somewhat achieves this, but I would like the input fields to remain hidden by default. <script language=" ...

Animating a Canvas to Follow Mouse Coordinates

I am looking for a way to animate a circle moving towards specific coordinates, similar to the game . I have attempted using the jquery animate() function, but it is too slow due to the constant updating of the target coordinates. Is there a faster metho ...

Having trouble setting a value as a variable? It seems like the selection process is not functioning properly

My Hangman game has different topics such as cities and animals. When a user selects a topic, the outcome should be a random item from that specific topic. For example: London for cities or Zebra for animals. Currently, I am only generating a random lett ...

When the redirect page includes a parameter, it has the ability to conceal the functionality of the subsequent page

I'm looking to redirect my page to another page while also triggering a hidden function on the next page. When I click on the redirect link, I want the page to redirect and for the function on the next page to be called as well. <script type="text ...

Unforeseen truncation issues within a table causing ellipsis to appear unexpectedly

I'm facing an issue with truncating text inside a table, and it's not working as expected. Can someone help me understand what I might be doing wrong? Edit: I need to ensure that the table width remains max-width: 100%; <script src="http ...

Changing the color of a pseudo element in Material-UI

I'm having trouble changing the border color of the ::after pseudo element on a standard text field from MUI. I've been unable to figure it out. <TextField id="standard-basic" label="Email" variant="standard"/> ...

What are the steps to integrate <br> in a JavaScript code?

I have recently started learning about web development and I'm facing a challenge with this implementation. var obj = [[{ name: "John", age: 30, city: "New York"}, { name: "Ken", age: 35, city: "New Orleans"}]]; ...

Revamping the hyperlinks in my collapsible menu extension

Is there a way to modify the links in this accordion drop menu so that they lead to external HTML pages instead of specific areas on the same page? I've tried various methods but can't seem to achieve it without affecting the styles. Currently, i ...

The function designed to create in-line TailwindCSS classNames may work inconsistently in React and NextJS environments

Currently, I am utilizing TailwindCSS to style a web application. One frustrating aspect is that when attempting to add before: and after: pseudo-elements, it must be done individually. For instance, take the navigation drop-down button styling: <span ...

What is the method to choose an invisible link without an identifier using Selenium WebDriver?

I am attempting to click on the link labeled 'User Requested'. This link only appears when hovering over the menu. This is the HTML code: <ul class="k-widget k-reset k-header k-menu k-menu-horizontal" id="menu" data-role="menu" tabindex="0" ...

Pressing a button within an HTML table to retrieve the corresponding value in that row

How can I click a button inside an HTML table, get the value on the same row and pass it to an input field called FullName? Thanks for your help! <td><?php echo $r['signatoryname'] ?></td> <td ...

Is there a way to align my green button beside the red button instead of below it?

I'm looking to rearrange the positioning of my green button on the screen. When I initially created the button, it ended up below my red button, but I want them to be displayed side by side. I haven't attempted any solutions because I am a beginn ...