DEV Community

Cover image for Responsive Masonry Layout with TailwindCSS in 2 Steps
kdrbek
kdrbek

Posted on • Edited on

Responsive Masonry Layout with TailwindCSS in 2 Steps

Masonry views on a website are visually appealing. Let's quickly create a carousel with you using TailwindCSS. This article assumes you have basic knowledge of Tailwind.

1. Configure index.css in your react-app

First of all, let's add @layer to your index.css file in src folder. We create masonry layout class for 3 different screen;

.masonry (1 column)
.masonry-sm (2 column)
.masonry-md (3 column)

@tailwind base; @tailwind components; @tailwind utilities; @layer utilities { @variants responsive { .masonry { column-gap: 1.5em; column-count: 1; } .masonry-sm { column-gap: 1.5em; column-count: 2; } .masonry-md { column-gap: 1.5em; column-count: 3; } .break-inside { break-inside: avoid; } } } 
Enter fullscreen mode Exit fullscreen mode

2. Use them inside className

Now you can use these classes as standard TailwindCSS feature. You should use them inside parent div.

<div className="masonry sm:masonry-sm md:masonry-md"> <div className="rounded-lg bg-gray-500 p-4 break-inside"> <p> lorem100 </p> </div> <div className="rounded-lg bg-gray-500 p-4 break-inside"> <p> lorem150 </p> </div> <div className="rounded-lg bg-gray-500 p-4 break-inside"> <p> lorem50 </p> </div> <div className="rounded-lg bg-gray-500 p-4 break-inside"> <p> lorem200 </p> </div> </div> 
Enter fullscreen mode Exit fullscreen mode

That is all. You now have a masonry layout that is simple to use and looks good.

Top comments (9)

Collapse
 
moniqu3 profile image
Monique

I've been struggling with this for quite a while now until I came across your article. Thanks a lot for posting this !

Collapse
 
mindpixellabs profile image
Mind Pixel

This is a very solid solution for masonry layouts with tailwind. Thank you!

Collapse
 
mortenebak profile image
Morten Bak

Thanks! :)

Collapse
 
liornn profile image
Lior Neu-ner

Worked great! Thank you

Collapse
 
lowcozy profile image
LowCozy

i only have a problem with ordering list

Collapse
 
aliashrafi051 profile image
Ali Ashrafi

Thanks man! but what about horizontal ordering? 🤔

Collapse
 
avik6028 profile image
Avik Kundu • Edited

Any fixes to this warning?

warn - The `@variants` directive has been deprecated in Tailwind CSS v3.0. warn - Use `@layer utilities` or `@layer components` instead. 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
richardsaseun profile image
Richie

Use this instead @avik6028

@layer utilities { .masonry { column-gap: 1.5em; column-count: 2; } .masonry-sm { column-gap: 1.5em; column-count: 2; } .masonry-md { column-gap: 1.5em; column-count: 3; } .break-inside { break-inside: avoid; } } 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
thrasher profile image
Enrico Monzeglio

Thank you very much :)