Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to have an image fit the height of grid container?

I did try to get a hint from: Controlling the size of an image within a CSS Grid layout

My code:

import { FC } from 'react';

import './style.css';

export const App: FC<{ name: string }> = () => {
  return (
    <div
      style={{
        display: 'grid',
        gridTemplateColumns: '1fr 1fr',
        border: '1px solid red',
        maxHeight: 250,
      }}
    >
      <img
        style={{ width: '100%', maxHeight: '100%', objectFit: 'cover' }}
        src="https://picsum.photos/id/237/200/300"
      />
      <h1>hello</h1>
    </div>
  );
};

Result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

code on Stackblitz: https://stackblitz.com/edit/stackblitz-starters-hy8g2s?file=src%2FApp.tsx

How can I have the image fit the height of the grid container, while taking the full available width (which is half of the container width, like it’s currently doing well) ? In case it’s not clear, the only change I want is for the height of the image to fit the height of the container. Also, I don’t want to use overflow: hidden. I want the image height to fit the height of the container while showing the full image.

>Solution :

Edit

Grid sets this annoying property min-height: max-content (or something like that) so you need to turn that off with min-height: 0 for it to fit (and min-width: 0 if you aren’t putting a dog picture in your app):

      gridArea: 'span 1',
      objectFit: 'cover',
      minHeight: '0',
      width: '100%',
      height: '100%',

Like this:
https://stackblitz.com/edit/stackblitz-starters-3rwrer?file=src%2FApp.tsx

Old answer

Use position: absolute.

https://stackblitz.com/edit/stackblitz-starters-cpbxvz?file=src%2FApp.tsx

But, it depends what you are trying to do, and its strange you have a CSS grid in two columns, but want to make your image cover both of them.

gridColumn: "span 2"

Might be closer to what you are aiming for.

https://stackblitz.com/edit/stackblitz-starters-3rwrer?file=src%2FApp.tsx

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading