Search code examples
javascripthtmlcsstailwind-cssnext.js14

Masonry Wall misalignment in Next.js using tailwind css


I have created an image gallery using tailwind CSS in Next.js 14. The issue is that the description for the grid elements at the bottom of the grid moves to next column.

Solution I tried:

  1. I used grid classes grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 for this problem but there were gaps between images which I don't want.

Current Output enter image description here

My code

<div className="mt-4 columns-1 md:columns-2 lg:columns-3 gap-x-8 ">
  {ProductsMockData.map((products) => { return (
  <div className=" group relative mb-4" key={products.id}>
    <div className=" w-full overflow-hidden rounded-md bg-gray-200 lg:aspect-none group-hover:opacity-75">
      <Image src={products.image} alt="Basic Tee in black." className="h-full w-full object-cover" unoptimized={true} width={500} height={500} />
    </div>
    <div className="mt-4 flex justify-between">
      <div>
        <h3 className="text-md text-primary">
          <Link href="#">
          <span aria-hidden="true" className="absolute inset-0"></span> {products.title}
          </Link>
        </h3>
        <p className="mt-1 text-sm text-secondary-foreground">
          {products.description}
        </p>
      </div>
      <p className="text-sm font-medium text-primary">
        {products.price}
      </p>
    </div>
  </div>
  ); })}
</div>

Help is appreciated :)


Solution

  • Ok so after spending quite some time with the tailwind css documentation, I was able to find the solution to my problem.

    I added class "break-inside-avoid" in <div className=" group relative mb-4" key={products.id}>, this resolved my problem.

    Output achieved

    enter image description here

    No more breaking of description section at the bottom, hope this helps someone.