Search code examples
htmlcss

Image overflowing container height when using a grid


I want two columns within a div. On the first column, there is an image. The problem i am facing is that it seems that the grid column will stretch the image width. Since the aspect ratio of the image is being preserved, that can cause the image height to overflow outside of the div.

.container {
  background: green;
}

.w-9\/12 {
    width: 75%;
}

.h-\[80vh\] {
    height: 80vh;
}

.grid-cols-2 {
    grid-template-columns: repeat(2, minmax(0, 1fr));
}

.grid {
    display: grid;
    color:blue;
}

.h-full {
    height: 100%;
}

.max-h-full {
    max-height: 100%;
}
<div class="h-[80vh] w-9/12 container">
<div class="grid grid-cols-2">
      <div class="h-full">
        <img src=https://picsum.photos/200/300 alt="" class="max-h-full" />
      </div>
      <div>
        <button>
          Close
        </button>
      </div>
</div>
</div>

How can i preserve the image aspect ratio while still making the image fill the width or fill the height of the grid (without the grid overflow the container div). This seems to work without the grid.


Solution

  • Try grid-auto-rows to set each row height.

    grid-auto-rows in the tailwind is auto-rows-[YOUR_VALUE]

    .container {
      background: green;
    }
    
    .w-9\/12 {
        width: 75%;
    }
    
    .h-\[80vh\] {
        height: 80vh;
    }
    
    .grid-cols-2 {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }
    
    .grid {
        display: grid;
        color:blue;
    }
    
    .auto-rows-\[80vh\] {
        grid-auto-rows: 80vh;
    }
    
    .h-full {
        height: 100%;
    }
    
    .max-h-full {
        max-height: 100%;
    }
    <div class="h-[80vh] w-9/12 container">
    <div class="grid grid-cols-2 auto-rows-[80vh]">
          <div class="h-full">
            <img src=https://picsum.photos/200/300 alt="" class="max-h-full" />
          </div>
          <div>
            <button>
              Close
            </button>
          </div>
    </div>
    </div>