Let’s say that I have an HTML image with predefined, hard-coded and immutable width and height values:
<img src="img.png" style="width: 800px; height: 600px" />
And a CSS rule to make all images responsive:
img {
max-width: 100%
}
The problem is that when the page is resized, the image’s aspect ratio is not preserved.
Is it possible to keep the aspect ratio, given that:
- I can’t change the inline style for the image
- But I can change the global CSS
Note: The solution has to be generic as width: 800px; height: 600px
is just a sample and the ratio could be anything.
5
Answers
Try using
aspect-ratio
. Based on your sizing of 800px x 600px that’s a ratio of 4/3 so you’d use:Instead of using img use div with background-image property. Like this
here is more info:
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_backgrounds_and_borders/Resizing_background_images
What you need is for the width and height to be relative to the same figure.
For example:
In this example, the width and height will be relative to the width of the page.
(the !important is to override the height and width defined in html)
If the inline styles are actually the intrinsic width and height of the image then all you have to do is to reset the height to
auto
. You can keep the width as it is since you havemax-width
.To do that you need to put a
width: 100%;
andheight: auto;
in responsive with media query. But in you image tag, you need tu put height and width properties for the SEO.So, you to put the image size by default.
Exemple :