Search code examples
htmlcsstailwind-csscss-grid

Is it possible to use Tailwind to create a responsive grid (dynamic number of columns that wraps to new row when appropriate)?


https://play.tailwindcss.com/gUoOBmaNxj was my attempt:

<div class="w-96 border-2 border-red-500">
  <div class="grid auto-cols-max grid-flow-col gap-2 border-2 border-black">
    <div class="w-20 bg-blue-500 p-4">1</div>
    <div class="w-20 bg-green-500 p-4">2 this one is taller</div>
    <div class="w-20 bg-red-500 p-4">3</div>
    <div class="w-20 bg-yellow-500 p-4">4</div>
    <div class="w-20 bg-purple-500 p-4">5</div>
    <div class="w-20 bg-pink-500 p-4">6</div>
    <div class="w-20 bg-indigo-500 p-4">7</div>
    <div class="w-20 bg-teal-500 p-4">8</div>
    <div class="w-20 bg-cyan-500 p-4">9</div>
    <div class="w-20 bg-gray-500 p-4">10</div>
  </div>
</div>

But you can see that it just creates 1 row and doesn't wrap.

grid

I don't understand the Tailwind grid docs (e.g. https://tailwindcss.com/docs/grid-auto-columns).

The red-bordered container represents the screen width.

I want people to be able to resize their screens and have the grid adjust.

But I don't want to need to use breakpoints like sm: and md: and specify a number of columns for each.


Solution

  • Consider applying grid-template-columns: repeat(auto-fill, <size>) or grid-template-columns: repeat(auto-fit, <size>) via a grid-cols-* class. The <size> will be up to you, since you have not specified any specification for the column sizes. Here's an example with 5rem:

    <script src="https://cdn.tailwindcss.com/3.3.3"></script>
    
    <div class="w-96 border-2 border-red-500">
      <div class="grid grid-cols-[repeat(auto-fill,5rem)] gap-2 border-2 border-black">
        <div class="w-20 bg-blue-500 p-4">1</div>
        <div class="w-20 bg-green-500 p-4">2 this one is taller</div>
        <div class="w-20 bg-red-500 p-4">3</div>
        <div class="w-20 bg-yellow-500 p-4">4</div>
        <div class="w-20 bg-purple-500 p-4">5</div>
        <div class="w-20 bg-pink-500 p-4">6</div>
        <div class="w-20 bg-indigo-500 p-4">7</div>
        <div class="w-20 bg-teal-500 p-4">8</div>
        <div class="w-20 bg-cyan-500 p-4">9</div>
        <div class="w-20 bg-gray-500 p-4">10</div>
      </div>
    </div>
    
    <div class="border-2 border-red-500">
      <div class="grid grid-cols-[repeat(auto-fill,5rem)] gap-2 border-2 border-black">
        <div class="w-20 bg-blue-500 p-4">1</div>
        <div class="w-20 bg-green-500 p-4">2 this one is taller</div>
        <div class="w-20 bg-red-500 p-4">3</div>
        <div class="w-20 bg-yellow-500 p-4">4</div>
        <div class="w-20 bg-purple-500 p-4">5</div>
        <div class="w-20 bg-pink-500 p-4">6</div>
        <div class="w-20 bg-indigo-500 p-4">7</div>
        <div class="w-20 bg-teal-500 p-4">8</div>
        <div class="w-20 bg-cyan-500 p-4">9</div>
        <div class="w-20 bg-gray-500 p-4">10</div>
      </div>
    </div>