0

When I use the <img> tag to render an image inside a container, the image scales its container to fit the browser in height but not width. Using the very same image with the help of the background-image property, the image stays within the limits of its container (the way its supposed to be). The thing is I want to use the <img> tag instead of the CSS property. Is there any way to make it work? I could resize the original image, but it's been bugging me for a while that I can't style it properly using CSS. I searched as best as I could for an answer but to no avail.

Note: I'm using a Sass compiler. The image provided is similar in size with the one I want to use 1500x2376.

1. The background-image property:

<div class="image">
    <div class="demo-image"></div>
</div>

.header-content{
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  height: 100%;

  .left-header{
    display: flex;
    align-items: center;
    position: relative;

    .image{
      height: 90%;
      width: 68%;
      margin-left: 4rem;
      background-color: #000;

      .demo-image{
        height: 100%;
        width: 100%;
        background-image: url("https://newyorkyimby.com/wp-content/uploads/2016/08/One-Journal-Square.jpg");
        background-size: cover;
      }
    }
  }
}

2. The <img> HTML tag:

<div class="image">
    <img src="https://newyorkyimby.com/wp-content/uploads/2016/08/One-Journal-Square.jpg" alt="Some image">
</div>

.image{
   height: 90%;
   width: 68%;
   margin-left: 4rem;
   background-color: #000;

   img{
     width: 100%;
     height: 100%;
     object-fit: cover;
   }
}
Rares
  • 33
  • 1
  • 4

1 Answers1

0

In the img, change 'height' to 'max-height', and set it to the value of the height in the class: image, I think this would regulate the height of the image, when it exceeds the set height, the object-fit will make it not protrude from the set height, as if you "cut" the photo, but you don't really cut it.

.image{
   height: 90%;
   width: 68%;
   margin-left: 4rem;
   background-color: #000;

   img{
     width: 100%;
     max-height: 90%;
     object-fit: cover;
   }
}
ai-zac
  • 1
  • 2
  • It worked, but the spacing of the image was imbalanced, so I used img{height: 90vh;} instead and it works as intended. – Rares Jul 09 '22 at 18:27
  • I think it works more when you don't use values like %, I used it with some containers. – ai-zac Jul 09 '22 at 21:58