Use Tailwind CSS to ensure fixed width and height of cards in CSS grid
P粉184747536
P粉184747536 2024-03-26 21:34:28
0
1
471

I'm building an app using Tailwind CSS and React, and in one of the views I have a grid of cards. Currently it looks like this:




As you can see, when I shrink the window, the cards squeeze into it. I want to make sure that the card size (width and height) always stays the same and if the number of cards doesn't fit in one row as the window gets smaller, it just moves to the next row.

Similar to (made with MS paint):




The size of the card remains fixed (same aspect ratio) even if the screen gets smaller.

This is what my code currently looks like:

grid:

<div>
    <ul className="grid grid-cols-1 gap-4 sm:grid-cols-2 sm:gap-4 md:grid-cols-6 md:gap-4 lg:grid-cols-8 lg:gap-4">
        {props.trips.map((trip: TTrip) => (
            <TripCard trip={trip} href={currentPath + trip.id} />
        ))}
    </ul>
</div>

card:

<li
        key={props.trip.id}
        className="card card-compact shadow-xl col-span-1 w-128 h-fit bg-gray-100 hover:bg-base-200"
    >
        <div className="relative w-128 h-32">
            <Image src="https://placeimg.com/500/225/arch" layout="fill" objectFit="cover" />
        </div>
        <div className="card-body">
            <h2 className="card-title">{props.trip.name}</h2>
            <h2>Time - Time</h2>
        </div>
    </li>

Know how to set it up using tailwind-css?

P粉184747536
P粉184747536

reply all(1)
P粉098417223

I know you want to use Grid to set it up, but unfortunately it's not the right tool for the job. Flexbox is best suited for your needs. This is a tailwind playground that displays the output you want. The playground I linked doesn't use NextJS like in your example. Therefore, I modified some things, like the images, since they are not NextJS specific.

I made some changes to the style, which I think is more effective. That said, I've moved the width setting from the image to the container div. You can further modify this setting as per your requirements.

In your setup, the code will translate roughly as follows.

// Grid
    {props.trips.map((trip: TTrip) => ( ))}
// Card
  • {props.trip.name}

    Time - Time

  • It looks like this:

    The biggest package

    Medium size without packaging

    Small without packaging

    Small, packaged

    The exact cutoff point where size and wrapping changes depends on how you decide to implement it. If you are not satisfied with the above points, you can simply modify the lg, md prefix according to your needs.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template