tailwind-cssflexboxgrid

Flexbox grid with 7 columns


I am creating a grid with tailwind and flexbox. Is it possible to create a 7 column grid? I know I can use width percentage but what would be the best practice here?


Solution

  • Actually the best solution would be to use CSS Grid instead Flexboxes to do this. Tailwind supports grid with up to 12 columns by default (docs).

    <div class="grid grid-cols-7">
      <div class="col-span-1">1</div>
      <div class="col-span-3">2</div>
      <div class="col-span-3">3</div>
    </div>
    

    If You really need to use flex:

    By default there are classes w-1/2, w-1/3, w-1/12 etc but not w-1/7. We can set width for div manually in style="" or CSS, but the best practice would be to extend Tailwind configuration.

    We need to add to tailwind.config.js new width classes (docs):

      module.exports = {
        theme: {
          extend: {
            width: {
    +         '1/7': '14.2857143%',
    +         '2/7': '28.5714286%',
    +         '3/7': '42.8571429%',
    +         '4/7': '57.1428571%',
    +         '5/7': '71.4285714%',
    +         '6/7': '85.7142857%',
            }
          }
        }
      }
    

    Now we can use our x/7 columns:

    <div class="flex">
       <div class="w-1/7">1</div>
       <div class="w-3/7">2</div>
       <div class="w-3/7">3</div>
    </div>
    

    If You only want to get 7 columns with equal width, then we do not need to extend config and use width classes at all:

    <div class="flex">
       <div class="flex-1">1</div>
       <!-- ... -->
       <div class="flex-1">7</div>
    </div>