CSS Grid 强制列数为奇数

and*_*oot 5 css firefox css-grid

我想创建一个响应式网格,随着窗口大小的增加添加额外的列,但列的总数始终是奇数。

我找到了一个适用于 Chrome/Opera/Safari 但不适用于 Firefox 的解决方案:

grid-template-columns: repeat(auto-fill, minmax(150px,1fr) minmax(150px,1fr)) minmax(150px,1fr);
Run Code Online (Sandbox Code Playgroud)

关于如何在 Firefox 中进行这项工作的任何建议?

CodePen:https ://codepen.io/andybarefoot/pen/MrOzod ? editors = 0100

Dan*_*eld 2

这是一个已知的 Firefox 错误,记录在网格错误中,没有建议解决方法。

  1. 重复符号应接受曲目列表

Repeat () 语法(来自规范)如下所示:

repeat( [ <positive-integer> | auto-fill | auto-fit ] , <track-list> )
Run Code Online (Sandbox Code Playgroud)

第一个参数指定重复次数。第二个参数是曲目列表,它会重复指定的次数。

Firefox 可以在重复函数的第二个参数中处理曲目列表,但前提是第一个参数是整数。

例如Firefox 可以处理这个grid-template-columns: repeat(3, 200px 100px);

但是,如果第一个参数是auto-fillor auto-fit-这就是 firefox bug

例如:firefox 在这里失败grid-template-columns: repeat(auto-fill, 200px 100px);


解决方法:(也适用于 Firefox)

repeat( [ <positive-integer> | auto-fill | auto-fit ] , <track-list> )
Run Code Online (Sandbox Code Playgroud)
body {
  background-color: #5F9E9D;
  margin: 0;
}

img {
  max-width: 100%;
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr) minmax(150px, 1fr)) minmax(150px, 1fr);
}

@-moz-document url-prefix() {
  .grid {
    grid-template-columns: repeat(auto-fill, calc(100vw / 3 - 5px));
  }

  @media (min-width: 750px) {
    .grid {
      grid-template-columns: repeat(auto-fill, calc(20vw - 5px));
    }
  }
  @media (min-width: 1050px) {
    .grid {
      grid-template-columns: repeat(auto-fill, calc(100vw / 7 - 5px));
    }
  }
  @media (min-width: 1350px) {
    .grid {
      grid-template-columns: repeat(auto-fill, calc(100vw / 9 - 5px));
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Codepen 演示

话虽这么说,一种解决方法可能是编写仅适用于 Firefox 的 CSS,它利用媒体查询来设置grid-template-columns具有固定列宽的属性,这样我们就可以确保列数为奇数。

我还没有触及标记,并且我添加了仅针对 firefox 的 css - 使用此方法

1) 只为 Firefox 封装额外的 CSS

@-moz-document url-prefix() {
    /* firefox only code */
} 
Run Code Online (Sandbox Code Playgroud)

2) 由于我们知道图像将显示在 3,5,7.. 列中,并且每个图像的最小宽度为 150px - 我们也可以生成媒体查询来为这些列创建布局。

.grid {
      grid-template-columns: repeat(auto-fill, calc(100vw / 3 - 5px));
  }


  @media (min-width:750px) { /* 150 * 5 = 750 */
    .grid {
      /* -5px to take the scrollbar into account */
      grid-template-columns: repeat(auto-fill, calc(20vw - 5px)); 
    }
  }

@media (min-width:1050px) { /* 150 * 7 = 1050 */
    .grid {
      grid-template-columns: repeat(auto-fill, calc(100vw / 7 - 5px));
    }
  }
Run Code Online (Sandbox Code Playgroud)

ETC...