As we enter 2021, a more widely supported and standards-compliant method for achieving this can be found using the CSS aspect-ratio property.
To implement this, you can set the height and width as follows:
.myimage {
width: 50%;
height: auto;
aspect-ratio: 1280 / 720;
}
With this approach, first, the width is calculated as 50% of the parent element's width. Then, by setting the height to auto and defining the aspect ratio, the correct height is determined dynamically.
It's important to note that even after the image has loaded, changes made with the aspect-ratio property persist. This means that if the specified aspect ratio doesn't match the image's actual aspect ratio, the image may appear stretched. To avoid this, it's recommended to include the "auto" value before the aspect ratio values.
aspect-ratio: auto 1280 / 720;
This method ensures that the defined aspect ratio is used until the browser determines the actual intrinsic aspect ratio of the image, at which point it reverts back to automatic sizing.
While this technique is not compatible with non-standard browsers like Internet Explorer and Safari, there is an alternative HTML solution available now. Most modern browsers utilize the height and width attributes of the image element to calculate the aspect ratio before applying CSS styles.
For instance...
<img src='myimage.jpg' class='myimage' width='1280' height='720' />
.myimage {
width: 50%;
height: auto;
}
By specifying the width and height attributes directly in the image tag, the appropriate vertical height is reserved, ensuring compatibility across different browsers including Safari. However, please review any browser-specific implementation notes.
In browsers like Chromium and Firefox, the CSS aspect-ratio property is utilized along with a "auto" prefix to maintain the calculated aspect ratio.
aspect-ratio: auto attr(width) / attr(height);
Notably, Safari currently lacks support for the aspect-ratio property. As a result, it requires additional considerations, particularly when implementing lazy loading for images via JavaScript. In such cases, a fallback image should be included to ensure proper spacing allocation.
In conclusion, incorporating height and width attributes within your image tags remains essential for optimal display consistency.