Responsive Masonry Image Grid In JavaScript

Category: Gallery , Javascript , Layout | January 16, 2023
Author:mcdavidlubega
Views Total:1,792 views
Official Page:Go to website
Last Update:January 16, 2023
License:MIT

Preview:

Responsive Masonry Image Grid In JavaScript

Description:

A fully responsive photo grid built on top of JavaScript and CSS flexbox.

The grid is Masonry-style, which means that the images are placed in a way that minimizes gaps and makes the grid look more natural. It’s responsive and adapts to different screen sizes, so it will look great on any device.

How to use it:

1. Create a container to hold the masonry image grid.

<div class="container">
  ...         
</div>

2. Load the main script ‘app.js’ at the end of the document.

<script src="app.js"></script>

3. Push your images to the grid.

// example images
const posts = [];
const images = [
  '1.jpg',
  '2.jpg',
  '3.jpg',
  // ...
];
let imageIndex = 0;
for (let i = 1; i <= 80; i++) {
  let item = {
    id: i,
    title: `Post ${i}`,
    image: images[imageIndex],
  };
  posts.push(item);
  imageIndex++;
  if (imageIndex > images.length - 1) imageIndex = 0;
}

4. The necessary CSS styles for the image grid.

.container{
  position: relative;
  width: 100%;
  display: flex;
  gap: 10px;
  padding: 100px 2vw;
}
.column{
  flex:1;
  display: flex;
  flex-direction: column;
  gap:10px;
}
.post{
  position: relative;
  overflow: hidden;
  width:100%;
}
img{
  width: 100%;
  border-radius: 5px;
  height: 100%;
}

5. Add a visually appealing overlay to the image when hovering over.

.overlay{
  position: absolute;
  top:0;
  left: 0;
  width:100%;
  height:100%;
  background:#161616;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity:0;
  transition:0.5s;
  border-radius: 5px;
}
.post:hover .overlay{
  opacity: 0.5;
  cursor: pointer;
}

You Might Be Interested In:


Leave a Reply