Home > database >  Equal-width columns in CSS with flexbox and Tailwind
Equal-width columns in CSS with flexbox and Tailwind

Time:09-14

I want to have a flexbox layout where three columns have the same width.

I have to use Tailwind in this case, but it doesn't change the CSS theory... which, as far as I know, says I need to give the three columns the same basis, and then let them grow freely (all of them will grow the same proportion because they have the same basis).

But it's not working. One of the column gets bigger and I don't know why.

Note: I added a border just to make it visually clear, but I don't need that.

.just-a-border {
border: 2px dotted purple;
}
<link href="https://unpkg.com/[email protected]/dist/tailwind.min.css" rel="stylesheet" />
<div >
  <div >
    <div >I want to have more words</div>
    <div >6 hours</div>
  </div>
  <div >
    <div >Yes</div>
    <div >1 hour</div>
  </div>
  <div >
    <div >No</div>
    <div >3 hours</div>
  </div>
</div>

Any idea to make it work?

CodePudding user response:

You used the classes from Tailwind CSS v3. So, if you upgrade your Tailwind CSS version to v3, your codes will be just working good.

If you want to keep the current version which is v2, you just need to update a few of class names in your current codes like below. basis-1 to flex-1, grow to flex-grow

<style>
  .just-a-border {
    border: 2px dotted purple;
  }
</style>

<div >
  <div >
    <div >I want to have more words</div>
    <div >6 hours</div>
  </div>
  <div >
    <div >Yes</div>
    <div >1 hour</div>
  </div>
  <div >
    <div >No</div>
    <div >3 hours</div>
  </div>
</div>

CodePudding user response:

It appears you are using Tailwind classes from version 3 while you are using version 2.2.19.

I added the following classes to your css and it now gives even columns.

.grow {
  flex-grow: 1;
}

.basis-1 {
  flex-basis: 0.25rem;
}

Also see the Play demo which uses your code, unchanged, and works as you would have expected.

https://play.tailwindcss.com/VjbHZcTiVH

.just-a-border {
border: 2px dotted purple;
}

.grow {
  flex-grow: 1;
}

.basis-1 {
  flex-basis: 0.25rem;
}
<link href="https://unpkg.com/[email protected]/dist/tailwind.min.css" rel="stylesheet" />
<div >
  <div >
    <div >I want to have more words</div>
    <div >6 hours</div>
  </div>
  <div >
    <div >Yes</div>
    <div >1 hour</div>
  </div>
  <div >
    <div >No</div>
    <div >3 hours</div>
  </div>
</div>

CodePudding user response:

You can use grid for that, instead of flex. Defining the number of columns with grid-cols-3 will create three columns of equal width and height.

See playground example and tailwind docs.

<div >
  <div >
    <div >I want to have more words</div>
    <div >6 hours</div>
  </div>
  <div >
    <div >Yes</div>
    <div >1 hour</div>
  </div>
  <div >
    <div >No</div>
    <div >3 hours</div>
  </div>
</div>
  • Related