DEV Community
Follow
Tailwind CSS masonry layout with columns, no JavaScript
To create a masonry layout in Tailwind CSS without JavaScript, apply columns-* classes to a container element. Ensure each item within the container receives the break-inside-avoid class to prevent content from splitting across columns. A gap class on the container spaces the columns, while a bottom margin on each item adds vertical spacing between elements. CSS columns naturally stack content downwards in the first column before moving to the next, which can alter the visual order of items. For a layout where items are ordered across, grid-lanes or JavaScript solutions are necessary. Native CSS masonry with display: grid-lanes is available in newer browser versions, placing items into the shortest available column. This approach offers better item ordering but has limited browser support currently. The CSS columns method, however, is widely supported and provides a straightforward implementation. A reusable React and TypeScript component demonstrates how to integrate this layout. The component accepts a list of items and a render function to display each one. By using Tailwind's utility classes, the masonry layout can be made responsive across different screen sizes. Adding width and height attributes to images prevents layout shifts as content loads. While native grid-lanes is a promising future solution, CSS columns remain the most reliable method for broad compatibility.