【问题标题】:Is there a way to prevent rows on having more elements than other rows when using masonry.js?使用 masonry.js 时,有没有办法防止行的元素多于其他行?
【发布时间】:2021-04-08 15:41:14
【问题描述】:

https://codepen.io/codepen_user_123/pen/xxgXYqY

$('.grid').masonry({
  itemSelector: '.grid-item',
  columnHeight: 1360,
  gutterHeight: 120;
});

所以我用它来创建一个非砌体类型的网格,但问题是有时我会在同一个元素上得到两个元素而不是一个。

下图描述了我正在寻找的内容:

您看到每行只有 5 个元素,在提供的 codepen 中,某些行的元素比其他行多,因为在该行的某些列上有足够的空间容纳 1 个以上的元素,所以有没有办法防止这会发生吗?我无法让它工作。

【问题讨论】:

    标签: css jquery-masonry


    【解决方案1】:

    我会给你一个奇怪的答案......但你甚至可能不需要砌体(以及 JS 和 jQuery)来实现你想要实现的目标。我相信在这种情况下,一个简单的 HTML 和 CSS 答案是合适的。 CSS 中有一个相对较新的特性,叫做CSS Grid。这是一个接近您想要的示例。布局的所有主要代码都在这里。

    .grid {
      grid-template-columns: repeat(5, 1fr);
      grid-auto-rows: auto;
      grid-gap: 12px;
      display: grid;
    }
    
    <div class="grid">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
      <div>6</div>
      <div>7</div>
      <div>8</div>
      <div>9</div>
      <div>10</div>
    </div>
    

    这是一个更完整的示例,其中包含与您上图类似的样式:

    .grid {
      grid-template-columns: repeat(5, 1fr);
      grid-auto-rows: auto;
      grid-gap: 12px;
      display: grid;
    }
    
    
    /* unnecessary stylistic changes below here */
    .grid {
      --color-1: rgb(252,151,36);
      --color-2: rgb(240,67,60);
      --color-3: rgb(97,125,138);
    }
    
    
    body {
      font-size: 32px;
      font-family: Arial;
      color: white;
      background-color: rgb(56,64,70)
    }
    
    .grid > * {
      text-align: center;
      padding: 0.7em;
    }
    
    .grid > *:nth-child(3n + 1) {
      background-color: var(--color-1);
    }
    
    .grid :nth-child(3n + 2) {
      background-color: var(--color-2);
    }
    
    .grid > *:nth-child(3n) {
      background-color: var(--color-3);
    }
    
    .grid > *:nth-child(4n + 1) {
      height: 75px;
    }
    
    
    .grid :nth-child(4n + 2) {
      height: 150px;
    }
    
    .grid :nth-child(4n + 3) {
      height: 50px;
    }
    
    .grid :nth-child(4n) {
      height: 125px;
    }
    <div class="grid">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
      <div>6</div>
      <div>7</div>
      <div>8</div>
      <div>9</div>
      <div>10</div>
    </div>

    【讨论】:

    • P.S.随时问我有关如何在 cmets 中做任何事情的任何问题。我不能保证我会马上回答,但我会尽量做到的。
    • 该解决方案是否适用于任何分辨率?我遇到了水平排序问题。
    • @caesar 不确定您的意思是否可以提供一个失败的最小示例并解释一下水平排序如何成为问题? (作为上述示例的不同分辨率的示例,这里是不同的更宽页面大小stackoverflow.com/questions/67007421/…
    • 啊,没关系,当我在没有 masonry.js 库的情况下使用 masonry 时,我遇到了订购问题。
    猜你喜欢
    • 2022-12-25
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多