Tailwind CSS - How to make a grid with different width columns

January 4, 2024 • Category - CSS, Tailwind CSS • 4,971 views
ShareShare on FacebookShare on Twitter

Overview

Tailwind CSS has become a popular choice among developers for its simplicity and flexibility in building responsive and stylish user interfaces.

In this blog post, we'll explore how to create a two-column grid as an example using Tailwind CSS, where the first column takes up 20% of the width, and the second column occupies the remaining 80% using 3 different methods to accomplish this.

Note: You can use these same methods to achieve any number of columns with any width percentages that you wish.

Option 1 - Using the col-span method

In this example we want to achieve a 20% / 80% split. So to do that, set the number of grid columns to 5. Then you can set the first column to span 1 grid column, and the second column to span 4 grid columns.

<div class="grid grid-cols-5 gap-4">

    <!-- First Column (20% width) -->
    <div class="col-span-1 bg-gray-300 p-4">
        <!-- Content -->
    </div>

    <!-- Second Column (80% width) -->
    <div class="col-span-4 bg-gray-500 p-4">
        <!-- Content -->
    </div>

</div>

Option 2 - Defining additional widths in tailwind.config.js

You can define additional grid widths by extending the theme in tailwind.config.js as shown below:

# tailwind.config.js

module.exports = {
  theme: {
    extend: {
      gridTemplateColumns:
      {
        '20/80': '20% 80%',
      }
    }
  }
}

You can then select that tailwind class and apply it to your html as shown:

<div class="grid grid-cols-20/80 gap-4">

    <!-- First Column (20% width) -->
    <div class="bg-gray-300 p-4">
        <!-- Content -->
    </div>

    <!-- Second Column (80% width) -->
    <div class="bg-gray-500 p-4">
        <!-- Content -->
    </div>

</div>

Option 3 - Using arbitrary/dynamic values with the JIT compiler

With the introduction of the JIT compiler (introduced in version 2.1+) and the ability to use arbitrary/dynamic values in some utilities, you can now do this without having to modify the tailwind.config.js file:

<div class="grid grid-cols-[20%_80%] gap-4">

    <!-- First Column (20% width) -->
    <div class="bg-gray-300 p-4">
        <!-- Content -->
    </div>

    <!-- Second Column (80% width) -->
    <div class="bg-gray-500 p-4">
        <!-- Content -->
    </div>

</div>

0 Comments


Leave a Comment

Share your questions, thoughts and ideas while maintaining a considerate tone towards others, thank you.

All fields are required - your email address will not be published.