Search code examples
htmlcssimagecss-grid

Why Isn't the image filling the whole div?


This is a part of my code.

<section id="worthGrid">
   <div class="element">
     <a href="#">
      <img src="./img/image1.jpg" alt="some text" />
     </a>
   </div>
   <div class="element">
     <a href="#">
      <img src="./img/image2.jpg" alt="some text" />
     </a>
   </div>
</section>
#worthGrid {
  display: grid;
  grid-template-columns: auto;
  grid-template-rows: 1fr 1fr;
  grid-template-areas:
    "element"
    "element";
}

.element {
  position: relative;
  text-align: center;
  background-color: grey;
}

.element img {
  object-fit: cover;
  display: block;
  width: 100%;
  height: auto;
}

The first image is 1200 * 700 and the second image is 1300 * 950 in dimensions. The second image is filling the whole div perfectly, but the first image is keeping some bottom regions empty. I have set the elements' background color grey to check if the image is filling it or not.

I have tried nearly everything but it's not filling the whole box no matter what I do. The only way, I can brute force the first image to fill the whole box fully is to set a fixed height like height: 200px.

And I have set the element position to relative for some other parts of my code. I have a caption in each image that I want to show over it


Solution

  • Okay, just as I was getting ready to post this question, I thought of setting the min-height: 100% and link height to 100%.

    .element img {
      width: 100%;
      height: auto;
      min-height: 100%; /*How did I miss this*/
    }
    
    .element a {
      height: 100%;
    }
    

    And it solved the problem. I don't know why I didn't think of that earlier. I tried almost everything else.

    Just leaving this post here then, if someone faces the same type of problem as me.