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

Modifying the color of the chosen item - ion-select

Can anyone help me with changing the color of the selected item on ion-select? I've tried several solutions without success. Any suggestions? Documentation: https://ionicframework.com/docs/api/select I attempted to use the color property, but it did ...

Footer alignment issue when using react-full-page is causing it to not lineup at the bottom of the page

Currently, I have integrated the react-full-page package into my project. However, after adding the Footer to the routes, I noticed that the footer is only visible in the second section of the page and does not appear at the bottom as expected. If you wan ...

A div positioned to the left is placed beneath another div

I am faced with a design challenge involving two divs. The first div is floated left, while the second div is floated right. In order to achieve a responsive layout, I need the first div to go under the second div when the viewport changes. Both divs conta ...

"Utilizing a custom CSS style for a half heart rating system

I am currently working on implementing a rating system using the font-awesome fa-heart class. While I have successfully colored the full heart, I am facing difficulty in filling only the first half of the heart in red. Despite my research efforts, all solu ...

When the onclick function is triggered, two or more characters will be displayed

Functionality: To input name and email, users must click on the virtual keyboard displayed on the screen. Characters entered will be shown in the input box. Implementation: The HTML keyboard interface and associated script have been developed successful ...

Prevent highlighting of empty spaces in HTML by disabling selection

My goal is to be able to identify the word that is clicked on screen using jQuery without selecting any white space. For example, if I click between the word "together" and the down arrow, it should not select anything in this scenario. To achieve this, I ...

Unable to dial phone numbers when clicking 'Click to call' link on Android devices

Within my Cordova android application, I have a link set up like this: <a href = "tel:011123456789">Click to Call</a> While this click-to-call functionality works smoothly in IOS, it seems to be hindered in Android by an issue such as: 11- ...

Ways to modify the color of every appearance of a term in an html grid using css

My HTML code includes an AngularJS table as shown below: <table id="searchTable"> <thead> <tr> <th>Index</th> <th>Observation</th> <th>Reported By</th> ...

Add a variety of pictures to the sub-items within the collapsible list view

I've been working on adding different images to child items based on conditions, using if-else statements to assign the appropriate image. It's functioning as intended but encountering a problem when expanding another parent - the images are bein ...

The background image and svgs are not displayed on laravel localhost/public/index.php, but they appear when using "php artisan serve"

I've created a beautiful Laravel project on my PC. The welcome.blade.php file in the project has a background image located in the: public/images/ directory. To display the images, I've used the following CSS: html, body { color: #f4f6f7; ...

What would cause this to result in a blank array?

I have a main component that contains multiple sub-components, which I navigate between by clicking on different elements. These sub-components are all Vue files. What I am trying to achieve is to dynamically highlight the active component when it is bein ...

Using an HTML img tag without success, despite having the correct link

My HTML img tags are not working even though the link is correct. I have been attempting to resolve this issue for quite some time by researching multiple websites and trying various solutions, but unfortunately, nothing seems to be working. All I want i ...

Using Firebase with the async pipe in Angular 5

I am struggling to implement async pipe in Angular firebase and encountering an error that I cannot resolve: ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' Utilizing the Firebase NoSQL database: { "bos ...

how to position one div above another using css

I currently have a page layout with 7 different div elements structured like this; <div id="container"> <div id="head"></div> <div id="A"> <div id="A1">A1</div> <div id="A2"></div> ...

Employing the html.validationmessagefor to display a client-side error notification

My text fields have server-side validation messages. The field 'title' is a required field on the server side with a '[Required]' data attribute in the class, but it only seems to be checked on a postback or form submit. I am saving the ...

The Modal Textarea refreshes each time it is clicked

Whenever I try to type on the modal with 2 textareas, it stops and exits the textarea. The issue seems to be with onChange={event => setTitle(event.target.value)}, but I'm not sure how to fix it. <Modal.Body> <form onSub ...

How to position a fixed element in relation to a wrapper div using HTML and CSS

I need assistance with positioning the floating box on the right side of the window on this particular page. My goal is to have this box relative to the white div containing all the text, so instead of it sticking to the window edge, it should float aroun ...

Creating a Dropdown Filter using Vanilla JavaScript

I am currently working on a project for one of my college courses, which involves creating a dropdown list filter using pure JavaScript to filter a grid of images in HTML/CSS. The main challenge I am facing is that this filter needs to be able to work with ...

Look through the contents of each child within a div to locate specific text, then conceal any that do not include it

I want to dynamically hide divs that do not contain the text I specify. Here is the code I have tried: var $searchBox = $('#search-weeazer'); $searchBox.on('input', function() { var scope = this; var $userDivs = $('.infor ...

What is the best way to create a blurred effect on an image during loading, and then transition to a sharp image once it is fully loaded?

I'm currently working on a project where I want the images to display as a blurred preview initially, and then become clear once fully loaded. This is similar to the feature seen on Instagram, where the app shows a blurred image before displaying the ...