I've spent some time looking for a Masonry gallery with a grid layout, but couldn't find one that suited my needs. So, I decided to create my own. I implemented a customElement with grid layout, but encountered an issue when trying to assign grid rows dynamically.
I would appreciate your feedback and assistance in improving my solution.
Some errors that I have identified are:
- Need to run twice for it to work properly
- Blank spaces appear when the image/container height is not a multiple of 100
HTML
<masonry-gallery></masonry-gallery>
JS
class MasonryGallery extends HTMLElement {
items = [
{ image:'https://unsplash.it/200/100/' },
{ image:'https://unsplash.it/200/200/' },
{ image:'https://unsplash.it/200/300/' },
{ ...}
]
constructor() {
super()
this.attachShadow({ mode: 'open' })
this.create()
this.append()
}
create() {
this.style.display = 'grid'
this.style.gridTemplateColumns = 'repeat(auto-fill, 200px)'
this.style.gridTemplateRows = 'repeat(auto-fill, 1fr)'
this.style.gridGap = '1rem'
this.style.gridAutoFlow = 'row dense'
}
append() {
this.items.map(item => {
const div = document.createElement('DIV');
const image = document.createElement('IMG')
image.src = item.image
div.appendChild(image)
this.shadowRoot.appendChild(div)
div.style.gridRow = 'auto / span ' + [...String(image.height)][0]
})
}
}
customElements.define('masonry-gallery', MasonryGallery)