Search code examples
cssflexboxtailwind-css

Tailwind: having equal width columns without repeating something like w-full in every column


I'm trying to make sense of the simplest way to create responsive equal-width columns with Tailwind, but ideally without having to repeat the same class on every column.

This works:

<div class="container mx-auto p-10">
  <div class="flex flex-col md:flex-row gap-8">
    <div class="md:flex-1 h-[100px] bg-gray-300" />
    <div class="md:flex-1 h-[100px] bg-gray-400" />
    <div class="md:flex-1 h-[100px] bg-gray-500" />
  </div>
</div>

As does this:

<div class="container mx-auto p-10">
  <div class="flex flex-col md:flex-row gap-8">
    <div class="w-full h-[100px] bg-gray-300" />
    <div class="w-full h-[100px] bg-gray-400" />
    <div class="w-full h-[100px] bg-gray-500" />
  </div>
</div>

But is there no simpler way than having to repeat md:flex-1 or w-full inside every column? Basically my question is how to make this behavior the default for all columns.


Solution

  • You could give the parent element a class name like parent

    <div class="container mx-auto p-10">
      <div class="parent flex flex-col md:flex-row gap-8">
        <div class="bg-gray-300" />
        <div class="bg-gray-400" />
        <div class="bg-gray-500" />
      </div>
    </div>
    

    Then in the CSS file try this:

    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
    .parent div{
      @apply w-40 md:flex-1 h-[100px];
    }