Making a masonry layout in tailwind like the Pinterest feed is a bit tricky.
While I was working on our blog I struggled to find something online on how to do this with Tailwind, so I'm writing down my approach to this, so if others face the same issue they can use this post as a resource.
When using CSS to make a grid of this type each row ends up having the same height.
How it works
So the approach to build this kinds of layouts ends up looking something like:
- Loop through your items N times, where N is the number of columns you're trying to get
- Create a parent grid and N child grids for each of your columns
Code example
If your N is 3 (so you want 3 columns) here's how your React code would end up looking like:
export const MasonryLayout = ({ posts }) => {
const firstColumn = props.posts.filter((_, index) => index % 3 === 0);
const secondColumn = props.posts.filter((_, index) => index % 3 === 1);
const thirdColumn = props.posts.filter((_, index) => index % 3 === 2);
return <div className="grid grid-cols-2 md:grid-cols-3 gap-4 mt-20">
<div className="grid gap-4">
{firstColumn.map((post) => (
<Article key={post.id} post={post} />
))}
</div>
<div className="grid gap-4">
{secondColumn.map((post) => (
<Article key={post.id} post={post} />
))}
</div>
<div className="grid gap-4">
{thirdColumn.map((post) => (
<Article key={post.id} post={post} />
))}
</div>
</div>;
};
Here's how this will end up looking like:
Hope this helps, and let me know if this ends up saving you some time!