Is there any way to force a certain number of items per row using flex box or any other way in CSS / tailwind, without stretching the item’s width?
For my case, lets assume 4 items per row:-
<script src="https://cdn.tailwindcss.com/3.4.3"></script>
<h1 class="mt-6">my failed attempt:-</h1>
<div class="flex flex-wrap bg-gray-300">
<div class="m-2 grow basis-1/5 bg-yellow-500 p-10"></div>
<div class="m-2 grow basis-1/5 bg-blue-500 p-10"></div>
<div class="m-2 grow basis-1/5 bg-orange-500 p-10"></div>
<div class="m-2 grow basis-1/5 bg-red-500 p-10"></div>
<div class="m-2 grow basis-1/5 bg-neutral-500 p-10"></div>
<div class="m-2 grow basis-1/5 bg-green-500 p-10"></div>
<!-- ... more unknown number of elements with unknown width -->
</div>
<h1 class="mt-6">what i want:-</h1>
<div class="flex">
<div class="m-2 bg-yellow-500 p-10"></div>
<div class="m-2 bg-blue-500 p-10"></div>
<div class="m-2 bg-orange-500 p-10"></div>
<div class="m-2 bg-red-500 p-10"></div>
</div>
<div class="flex">
<div class="m-2 bg-teal-500 p-10"></div>
<div class="m-2 bg-cyan-500 p-10"></div>
<div class="m-2 bg-stone-500 p-10"></div>
<div class="m-2 bg-pink-500 p-10"></div>
</div>
<div class="flex">
<div class="m-2 bg-green-500 p-10"></div>
<div class="m-2 bg-black p-10"></div>
<div class="m-2 bg-slate-500 p-10"></div>
</div>
2
Answers
Try
grid
,grid-cols-*
,gap-*
Tailwind CSS documentation for reference
Use this grid-cols-* with Tailwind CSS and replace * with "n" number of columns you want and add grid before this. If you want gap between these columns then you can use gap-*.