Skip to content
Advertisement

Image strecting while fit to parent container

I have a image which is stretched. I want image fit to parent container for responsiveness and don’t want to loose aspect ratio of image Sample code to explain logic

    <div style="width: 65%, height: 40vh ">
    <RegionSelect>
    <img src="image-src-here" alt="" style="width: 100%, height: 100%;"/>
    </RegionSelect>
    </div>

RegionSelect Component is used to draw bounding box with given coordinates

Advertisement

Answer

Use a background image. background-size: contain will aspect-fit it to the container. background-size: cover will aspect-fill the container.

div
{
  background-image: url(https://via.placeholder.com/200x300);
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  width: 300px;
  height: 300px;
  border: 3px solid black;
}
<div></div>

div
{
  background-image: url(https://via.placeholder.com/200x300);
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  width: 300px;
  height: 300px;
  border: 3px solid black;
}
<div></div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement