0

I am trying to create a horizontal masonry grid using Swiper.js to arrange tags in 2 rows.

However, I am encountering two issues with my current implementation using Swiper.js:

The width is not calculated correctly, causing the last item to be cut off. I want to implement a masonry layout, but due to the styling being set to flex, the items do not align closely together and the child widths are being determined by a larger width.

I have looked through various issues on GitHub but couldn't find the answer I was looking for.

If anyone has encountered and resolved similar issues, please help.

The final layout I want to achieve is as follows:

finally-want-layout Here's my demo

1 Answer 1

0

This step can help

function adjustMasonryLayout() {
  var slides = document.querySelectorAll('.swiper-slide');
  var containerWidth = document.querySelector('.swiper-container').offsetWidth;
  var rowHeight = 0;

  slides.forEach(function(slide, index) {
    var slideWidth = slide.offsetWidth;
    var positionTop = 0;

    if (index % 2 !== 0) {
      positionTop = rowHeight + 10; 
    } else {
      rowHeight = Math.max(rowHeight, slide.offsetHeight);
    }

    slide.style.position = 'absolute';
    slide.style.left = (Math.floor(index / 2) * (slideWidth + 10)) + 
  'px'; 
    slide.style.top = positionTop + 'px';
  });

  document.querySelector('.swiper-wrapper').style.height = (rowHeight * 
  2 + 10) + 'px'; // Adjust the spacing between rows
}

Set your HTML To support swipper

<div class="swiper-container">
  <div class="swiper-wrapper">
    <div class="swiper-slide">Tag 1</div>
    <div class="swiper-slide">Tag 2</div>
    <div class="swiper-slide">Tag 3</div>
    <div class="swiper-slide">Tag 4</div>
    <div class="swiper-slide">Tag 5</div>
    <div class="swiper-slide">Tag 6</div>
    <!-- Add more slides as needed -->
  </div>
</div>

Align your grid

.swiper-container {
  width: 100%;
  height: auto;
}

.swiper-wrapper {
  display: flex;
  flex-wrap: wrap;
}

.swiper-slide {
  flex: 0 0 auto;
  width: auto; 
  margin: 0 5px; 
  background-color: #f0f0f0;
  padding: 10px;
  box-sizing: border-box;
}
2
  • Thank you for your answer. But it doesn't work the way you want it to. I will take a little more time to study and reply if I succeed.
    – Geon
    Commented Jul 8 at 15:29
  • Alright - its all good
    – Ugwu Somto
    Commented Jul 8 at 20:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.