Introducing the lightest and most efficient Masonry grid available — StackGrid — powered by pure vanilla JavaScript, no dependencies required.
This grid is perfect for those who want a lightweight and easy-to-implement solution for creating a dynamic, masonry-style image gallery layout on their website. With a minimal codebase and fast performance, this grid will have you up and running in no time.
This vanilla JavaScript Masonry grid is not only lightweight and easy to implement, but it is also fully responsive. As the screen width changes, the grid will automatically adjust the size and position of the cards to create a seamless and visually appealing layout. No need to worry about creating separate grid systems for different screen sizes, this grid handles it all with ease.
This small grid is compatible with the latest browsers, both desktop and mobile.
The grid adjusts its layout dynamically based on the available space and the number of images.
Setting Up
First, include the HTML structure for your gallery:
<div class="stack-container" max-width="640" min-width="320" gutter="5">
<div class="stack-card">
<div class="header">
<div class="title">Card Title</div>
</div>
<div class="content">Card image description</div>
<img src="image1.jpg">
</div>
<!-- Add more stack-card elements as needed -->
</div>
Replace image1.jpg
with the URLs of your image and customize the content and titles as required.
Next, add the provided JavaScript code to your project. This code dynamically adjusts the size and position of the gallery cards based on the available space.
How to Use
There is only one step: include the script: Place the JavaScript code in a <script>
tag at the end of your HTML body or in an external JavaScript file linked to your HTML document. Based on the HTML classes above, the grid will self-initialize.
How It Works
stackGridResizeCards
: This function calculates and sets the width of each card based on the container width, minimum and maximum card widths, and gutter size. It then callsstackGridPositionCards
to position the cards within the grid.stackGridPositionCards
: This function positions the cards within the grid layout. It calculates the left and top positions of each card based on the column and the position of other cards in the same column.stackGridWatchForResize
: This function continuously monitors the container width for changes. If the width changes, it callsstackGridResizeCards
to adjust the layout accordingly.
Demo
See a demo below.