This JavaScript code snippet helps you to create a responsive masonry grid layout. It counts items and renders rows and columns dynamically. You can easily integrate this grid layout for image galleries, posts, or content cards.
How to Create JavaScript Masonry Grid Layout
1. First of all, create a div element with a class name “wrapper” and place div elements with the class name “item” inside it. You can specify a different height for each item that will be automatically adjusted in the masonry layout. Inside the item, you can place any content that you want to display as a masonry grid layout.
<div class="wrapper"> <div class="item" style="height: 90px;">1</div> <div class="item" style="height: 200px;">2</div> <div class="item" style="height: 80px;">3</div> <div class="item" style="height: 120px;">4</div> <div class="item" style="height: 290px;">5</div> <div class="item" style="height: 200px;">6</div> <div class="item" style="height: 250px;">7</div> <div class="item" style="height: 70px;">8</div> <div class="item" style="height: 70px;">9</div> <div class="item" style="height: 50px;">10</div> <div class="item" style="height: 120px;">11</div> <div class="item" style="height: 260px;">12</div> </div>
2. After that, define the basic CSS styles for the masonry layout as follows:
.wrapper { width: 960px; margin: 0 auto; overflow: hidden; padding: 0px 0px 10px 10px; } .wrapper .col { float: left; width: 25%; } .wrapper .col .item { background: #ccc; display: block; margin: 10px 10px 0px 0px; padding: 10px; }
3. Finally, add the following JavaScript code and done.
var totalRows = 4, itemCol = 0; for(var rowCount = 0; rowCount < totalRows; rowCount++){ newCol = document.createElement('div'); newCol.className = 'col'; document.getElementsByClassName('wrapper')[0].appendChild(newCol); } for(var itemCount = 0; itemCount < document.getElementsByClassName('item').length; itemCount++){ document.getElementsByClassName('col')[itemCol].appendChild(document.getElementsByClassName('item')[0]); if(itemCol < totalRows - 1){ itemCol++; } else { itemCol = 0; } }
That’s all! hopefully, you have successfully integrated this masonry grid layout code snippet into your project. If you have any questions or facing any issues, feel free to comment below.
Similar Code Snippets:
I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.