skip to Main Content

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.

2

Answers


  1. 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>
    Login or Signup to reply.
  2. you can use the css property object-fit with the value contain. when you give the property object-fit to your image’s class. so without overflowing your image will be fit within the grid and also it’s aspect ratio remains maintain. here is the example:

    .max-h-full {
        max-height: 100%;
        object-fit: contain;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search