You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Isotope.js实现瀑布流布局时,如何消除异常右侧边距?

Isotope瀑布流网格缩放时右侧异常边距问题

使用Isotope结合原生JS实现瀑布流网格画廊布局,正常状态下运行正常,但窗口缩放时,masonry元素右侧会出现异常边距,且视口尺寸越小,该边距越大。Chrome开发者工具中无法定位到该边距对应的内边距、外边距等样式,已给masonry元素添加蓝色背景以便直观查看问题。

CSS代码

:root {
  font-family: "Inter", sans-serif;
  line-height: 1.5;
  font-weight: 400;

  font-synthesis: none;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  -webkit-text-size-adjust: 100%;
  box-sizing: border-box;
  scroll-behavior: smooth;
}

body {
  background-color: white;
  scrollbar-width: none;
  width: 100%;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body::-webkit-scrollbar {
  display: none;
}

.masonry-grid {
  margin: 0 auto;
  width: 100%;
  max-width: 1440px;
  background-color: royalblue;
}
.masonry-grid,
.masonry-grid * {
  box-sizing: border-box;
}

.hidden {
  display: none !important;
}

.item {
  position: relative;
  width: calc(100% - 10px);
  margin-bottom: 10px;
  border-radius: 20px;
}

.item img {
  width: 100%;
  display: block;
  border-radius: 20px;
  transition: all 0.3s;
}

.item-info {
  display: none;
}
/* Responsive breakpoints */
@media (min-width: 600px) {
  .item {
    width: calc(50% - 10px);
  }
}

@media (min-width: 960px) {
  .item {
    width: calc(33.33% - 10px);
  }
}

@media (min-width: 1280px) {
  .item {
    width: calc(25% - 10px);
  }
}

@media (min-width: 1600px) {
  .item {
    width: calc(20% - 10px);
  }
}

JS代码

let iso

window.onload = function () {
  const grid = document.querySelector(".masonry-grid")
  const filterButtons = document.querySelectorAll(".filter-buttons button")

  // Initialize Isotope after ensuring images have loaded
  imagesLoaded(grid, function () {
    iso = new Isotope(grid, {
      itemSelector: ".item",
      layoutMode: "masonry",
      containerstyle: null,
      masonry: {
        columnWidth: ".item",
        gutter: 12,
        itemSelector: ".item",
      },
    })
  })

  // Re-layout on window resize
  window.addEventListener("resize", () => {
    iso.layout()
  })
}

已尝试的解决方案(均无效)

  • 调整box-sizing、object-fit相关设置
  • 在窗口视口尺寸变化时重新初始化Isotope以重绘瀑布流网格
  • 使用Chrome和Firefox开发者工具排查样式问题
  • 通过搜索引擎及AI工具获取并尝试多种解决方案

急需技术帮助,感谢!


内容的提问来源于stack exchange,提问作者JackRussell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 17:24:58