Search code examples
reactjsnext.jstailwind-css

How to make images same size Next Image component


I have a NextJS app for which you can find codesandbox here where I am rendering a list of products. I am using Tailwind CSS for styling. I have a card where I am rendering the image for each product. I am using the NextJS Image component. However, I am having a hard time manipulating that component to get the images to look how I want them to look.

I want each image to be the same size and I want the images centered on the card. This is the code I have:

const products = [
  {
    name: "MIATONE QBOX Bluetooth 5.0 Speakers",
    image:
      "https://jevonc-next-ecommerce.s3.us-east-2.amazonaws.com/1696992686102-1a11dd34-66a9-4ca4-b7aa-cb2fd0015d4f.webp",
    price: 39.99,
  },
  {
    name: "TOZO PA1 Bluetooth Speakers",
    image:
      "https://jevonc-next-ecommerce.s3.us-east-2.amazonaws.com/1696992546850-4ffe9c74-9f1c-4c1e-9576-ebc8d6a12498.webp",
    price: 35.99,
  },
  {
    name: "Taylor Swift graphic tee",
    image:
      "https://jevonc-next-ecommerce.s3.us-east-2.amazonaws.com/1696991827463-e8040010-7379-4eef-b425-50c79a559df8.jpeg",
    price: 29.99,
  },
  {
    name: "Tupac t-shirt",
    image:
      "https://jevonc-next-ecommerce.s3.us-east-2.amazonaws.com/1696969647330-8efe7e9f-6ab0-43e4-9d90-776702902908.jpeg",
    price: 27.99,
  },
];
export default function Home() {
  return (
    <div className="grid grid-cols-4 gap-10 py-4 px-6">
      {products.map((product, idx) => (
        <div key={idx}>
          <div className="bg-white h-[200px] relative p-5 rounded-md">
            <Image
              src={product.image}
              alt={product.name}
              height={150}
              width={150}
            />
          </div>
          <h2>{product.name}</h2>
          <span>${product.price}</span>
        </div>
      ))}
    </div>
  );

This is the result:

enter image description here

Even though I set all the images height and width to 150px, they still seem to be coming out different sizes. Some are contained within the card while others are not, why? How can I fix this?


Solution

  • here is the CSS I used:

    • flex justify-center items-center on the div that wraps the image, to center it horizontally and vertically
    • object-contain h-[150px] w-[150px] on the Image component
      • object-contain to maintain the image aspect ratio while filling the content box
      • h-[150px] w-[150px] because Tailwind comes with default img height: auto which will stretch the image beyond the content box

    you may also need to use grid-cols-2 md:grid-cols-4 in the div that wraps all products so only two products are displayed on smaller screens

    codesandbox example:

    Edit interesting-glitter-t9qxrl