通过动态CSS Grid图像库进行映射

时间:2019-03-14 13:17:35

标签: html css reactjs css3 css-grid

我正在尝试通过我的Gatsby项目中的图像文件夹映射数组,并同时在CSS网格库中相应地显示它们:

enter image description here

如果我依次写所有元素,则可以很容易地做到这一点,但是当我映射图像时,似乎无法为每个元素设置特定的网格模板区域。参见下面的代码:

render={data => (
            <div
              style={{
                display: "grid",
                gridTemplateColumns: "1fr 1fr",
                gridTemplateAreas: "'a b'",
                gridGap: "15px",
                border: "1px solid red",
              }}
            >
              {data.source.edges.map(({ node }, i) => (
                <>
                  <Image
                    style={{ gridArea: "a", border: "1px solid red" }}
                    key={i}
                    fluid={node.childImageSharp.fluid}
                  />
                  <h1 style={{ gridArea: "b", border: "1px solid red" }}>B</h1>
                </>
              ))}
            </div>
          )}

如何映射图像并将其显示为上图,只有前两个图像占据50%的网格,所有其他行占据25%的网格?

1 个答案:

答案 0 :(得分:2)

您已经在使用gridTemplateColumns在网格中定义列了-因此您可以完全省略gridTemplateAreas。参见下文,了解您的代码目前如何简化为原始CSS:

.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 15px;
  border: 1px solid red;
}

img {
  border: 1px solid red;
}

h1 {
  border: 1px solid red;
}
<div class="wrapper">
  <img src="https://via.placeholder.com/400" />
  <h1>B</h1>
  <img src="https://via.placeholder.com/400" />
  <h1>B</h1>
  <img src="https://via.placeholder.com/400" />
  <h1>B</h1>
  <img src="https://via.placeholder.com/400" />
  <h1>B</h1>
</div>

现在要获取布局,您可以使用下面的4 x 2布局,对前两个图像使用grid-template-columns: repeat(4, 1fr)grid-column: span 2

.wrapper {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 15px;
  border: 1px solid red;
}

.wrapper img:first-child,
.wrapper img:nth-child(2) {
  grid-column: span 2;
}

img {
  border: 1px solid red;
  width: 100%;
  grid-column: span 1;
}

h1 {
  border: 1px solid red;
}
<div class="wrapper">
  <img src="https://via.placeholder.com/200" />
  <img src="https://via.placeholder.com/200" />
  <img src="https://via.placeholder.com/200" />
  <img src="https://via.placeholder.com/200" />
  <img src="https://via.placeholder.com/200" />
  <img src="https://via.placeholder.com/200" />
</div>

对于jsx,您可以使用以下内容:

render={data => (
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(4, 1fr)",
            gridGap: "15px",
            border: "1px solid red",
          }}
        >
          {data.source.edges.map(({ node }, i) => (
            <>
              <Image
                style={{ width: "100%", border: "1px solid red", gridColumn: i < 2 ? 'span 2':'span 1'}}
                key={i}
                fluid={node.childImageSharp.fluid}
              />
            </>
          ))}
        </div>
      )}