Search code examples
htmlcsscss-grid

Set image to 100% height of the grid row that has its height based on its content


I'm trying to make a layout with CSS grid, something like this |_|, but upside-down.

.parent{
    width:500px;
    padding:10px;
    background-color:grey;
    display:grid;
    grid-template-areas:
    "div1 div1"
    "div2 div3";
    grid-template-columns:auto 1fr;
    gap:10px;
}

.d1{
    grid-area:div1;
    background-color:pink;
}
.d2{
    grid-area:div2;
    background-color:beige;
}
.d2 p{
  margin:0;
}
.d3{
    grid-area:div3;
    background-color:aqua;
    display:flex;
    justify-content:flex-end;
    
}
.d3 img{
    grid-area:div3;
    background-color:aqua;
    height:200px;
    aspect-ratio:1/1;
    object-fit:cover;
}
<div class="parent">
  <div class="d1">DIV 1 Lorem ipsum dolor sit amet</div>
  <div class="d2">
    <p>DIV 2 Lorem ipsum</p>
    <p>DIV 2 Lorem ipsum</p>
    <p>DIV 2 Lorem ipsum</p>
    <p>DIV 2 Lorem ipsum</p>
  </div>
  <div class="d3"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/29841/dog.jpg"></div>
</div>

Right now, the image is set to a fixed height of 200px. Without it it would have its native size (way too big) What I'm trying to do is to set the image to be the same height as DIV2 (that has no fixed height). How can I do that?


Solution

  • add

    position: relative;
    

    to .d3 and then to the .d3 image add

    position: absolute;  
    top: 0;
    height: 100%;
    width: 100%;
    

    you can then remove the height.