html – Can images in the CSS 'grid-template-columns' be cropped to be square and still be responsive?-ThrowExceptions

Exception or error:

I have a responsive photo grid that works perfectly when the photos are square. Unfortunately some of the photos will be taller than they are wide and vice versa so I want them to be cropped to be square, maintain the aspect ratio, and be responsive like the square photos.

If the height is taller than width then I would like the width to be 100% and the vertical overflow to be hidden and vice versa if the opposite is true for the width and height.

I am using React so I don’t know if the solution would come from React, CSS, or JQuery.

enter image description here

My images are coming from an array, so to replicate my situation you may want fill an array of image URLs for React to map.

<div className='grid-box'>
  {Object.values(apiResponse.slice(0, (page+1)*6)).map((value, index) => 
  <a target="_blank" rel="noopener noreferrer" href={}>
    <div className="imagex">
      <img src={value.image} className="image"/>


.image {object-fit: cover; width:100%; overflow: hidden; height: auto; position: relative}
.imagex { position: relative;}
.grid-box {display: grid; grid-template-columns: auto auto auto; position: relative;}

NOT A DUPLICATE because I tried the other popular Stack Overflow solution to this with this CSS, but this created giant images that went off the screen.

.imagex{ width:80%; padding-bottom:80%; margin:1em auto; overflow:hidden;
  position:relative; background:#000 }
.imagex image { position:absolute; width:auto; min-width:100%; min-height:100%;}
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *