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粉0984172232024-03-27 18:30:06
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// Card{props.trips.map((trip: TTrip) => (
))}
It looks like this:
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.