【问题标题】:React/Gatsby: Using CSS grid with alternating number of columns in each rowReact/Gatsby:使用每行交替列数的 CSS 网格
【发布时间】:2020-07-24 08:35:14
【问题描述】:

我正在尝试创建一个交替每行中的列数的网格布局。因此,例如,第一行将有一列,第二行将有两列,然后第三行将返回一列。此时,我只有一个每行有两列的网格。

有人对如何做到这一点有任何建议吗?谢谢!

这是我现在拥有的:

<div className="grid grid-cols-2 gap-10">
  {projects.map(({ node }, index) => {
    const title = node.frontmatter.title || node.fields.slug
    const client = node.frontmatter.client
    const category = node.frontmatter.category
    const image = node.frontmatter.image.childImageSharp.fluid
    const description = node.frontmatter.description

    return (
      <div className="col-span-1">
        <Link to={node.fields.slug}>
          <BgImg fluid={image} className="h-104 bg-cover bg-no-repeat flex flex-col justify-end hover:shadow-2xl transition-all ease-linear duration-300" key={node.id}>
          </BgImg>
        </Link>
        <div className="py-5">
          <h3 className="text-2xl font-regular"><span className="font-semibold">{client}</span><span className="mx-1">&mdash;</span>{title}</h3>
          <p className="text-xl mb-4 font-light">{description}</p>
        </div>
      </div>
    )
  })}
</div>

【问题讨论】:

  • 会很短,使用取模:)

标签: css reactjs css-grid gatsby


【解决方案1】:

如果您希望 1 列的行像这样跨越整个宽度:

[content] [content]
[      content    ]
[content] [content]

而不是这样:

[content] [content]
[content]
[content] [content]

那么这在 TailwindCSS 中应该相当简单,如下所示:

<div className="grid grid-cols-2 gap-10">
  {projects.map(({ node }, index) => {
    const title = node.frontmatter.title || node.fields.slug
    const client = node.frontmatter.client
    const category = node.frontmatter.category
    const image = node.frontmatter.image.childImageSharp.fluid
    const description = node.frontmatter.description

    return (
      <div className={index % 3 == 2 ? "col-span-2" : "col-span-1"}>
        <Link to={node.fields.slug}>
          <BgImg fluid={image} className="h-104 bg-cover bg-no-repeat flex flex-col justify-end hover:shadow-2xl transition-all ease-linear duration-300" key={node.id}>
          </BgImg>
        </Link>
        <div className="py-5">
          <h3 className="text-2xl font-regular"><span className="font-semibold">{client}</span><span className="mx-1">&mdash;</span>{title}</h3>
          <p className="text-xl mb-4 font-light">{description}</p>
        </div>
      </div>
    )
  })}
</div>

【讨论】:

  • 是的,这太完美了!谢谢!这是一个比我想出的更清洁的解决方案
  • @taylor018 很高兴它有效!如果我的回答是正确的,你能接受吗?
猜你喜欢
  • 2021-02-17
  • 1970-01-01
  • 1970-01-01
  • 2014-05-16
  • 2018-11-15
  • 2017-03-21
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
相关资源
最近更新 更多