I use Tailwind CSS to style cards within a flex container. Initially, I centered the cards horizontally and vertically using items-center
and justify-center
. However, I encountered an issue where when there are only a few cards, they leave ample space between them. To address this, I tried using justify-start
, which resolved the spacing problem, but it caused the cards not to be centered correctly within the container.
My current setup:
<main className="max-w-[1200px] mx-auto my-20 flex flex-wrap items-center justify-start gap-5">
{series &&
series.map(
(serie) =>
serie.backdrop_path &&
serie.overview &&
!("success" in serie) && (
<div
className="w-[170px] max-w-sm lg:w-[220px] rounded text-slate-200 p-2 flex-shrink-0"
key={serie.id}
>
<DataCard dataType={serie} />
</div>
)
)}
</main>
And here is the current result:
What I want it to be:
I would like to know how I can maintain the alignment of the cards to the start of the container while ensuring they are centered horizontally within it. Any suggestions or insights on how to achieve this would be greatly appreciated.
2
Answers
Using
flex-wrap
would help you outExample:
Result:
Here I’ve used
flex-wrap
in the parent. You can use the same method to fix your problem.You cannot achieve that with just flex box, you have to give max-width to container, here you can learn more.
By the way I recommends you to use grid layout in this case