How do you create a responsive grid in TailwindCSS?

clock icon

Asked 1 year ago

message icon

1

eye icon

3

I’m working on a layout in my React project where I need to display a set of items (like cards or images) in a grid format that adapts to different screen sizes.

I’ve seen that TailwindCSS has utilities like grid, grid-cols-*, and gap-*, but I’m not fully sure how to use them in a responsive way — especially when I want, for example, 1 column on mobile, 2 on tablets, and 4 on desktops.

1 Answer

You can control the number of grid columns at different screen sizes using Tailwind’s responsive prefixes like sm:, md:, lg:, xl:, etc.

Here’s an example of a responsive grid that:

  • shows 1 column on mobile,
  • 2 columns on small screens (≥640px),
  • 3 columns on medium screens (≥768px),
  • and 4 columns on large screens (≥1024px):
1<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
2 <div className="bg-gray-200 p-4">Item 1</div>
3 <div className="bg-gray-200 p-4">Item 2</div>
4 <div className="bg-gray-200 p-4">Item 3</div>
5 <div className="bg-gray-200 p-4">Item 4</div>
6 {/* More items */}
7</div>
1<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
2 <div className="bg-gray-200 p-4">Item 1</div>
3 <div className="bg-gray-200 p-4">Item 2</div>
4 <div className="bg-gray-200 p-4">Item 3</div>
5 <div className="bg-gray-200 p-4">Item 4</div>
6 {/* More items */}
7</div>

Explanation:

  • grid: enables grid layout.
  • grid-cols-1: default is 1 column.
  • sm:grid-cols-2: when screen width ≥ 640px, switch to 2 columns.
  • md:grid-cols-3: when ≥ 768px, switch to 3.
  • lg:grid-cols-4: when ≥ 1024px, use 4 columns.
  • gap-4: adds spacing between grid items.

1

Write your answer here

Top Questions