How to prevent an image from stretching and instead show the image based on screen size in HTML and CSS?
To prevent an image from stretching and instead show the image based on screen size, you can use the CSS object-fit
property.
The object-fit
property specifies how an image or video should be resized to fit its container. By default, the object-fit
property is set to fill
, which stretches the image to fit the container. However, you can set the value to contain
, which scales the image while preserving its aspect ratio to fit within the container without stretching it.
Here's an example:
<img src="path/to/image.jpg" style="object-fit: contain; width: 100%; height: 100%;">
In this example, we're setting the object-fit
property of the img
element to contain
, which scales the image to fit within the container while preserving its aspect ratio. We're also setting the width
and height
properties to 100%
, which makes the img
element fill its parent container while maintaining its aspect ratio.
Note that the object-fit
property is not supported in some older browsers, so you may need to use a polyfill or fallback approach to ensure that the image displays correctly in those browsers.
Comments
Post a Comment