Search code examples
cssreactjscss-gridgatsby

React/Gatsby: Using CSS grid with alternating number of columns in each row


I'm trying to create a grid layout that alternates the number of columns in each row. So, for example, the first row would have one column and the second row would have two columns then the third row would go back to one column. At this point, I only have a grid that has two columns for each row.

Anyone have any suggestions on how to do this? Thanks!

Here's what I have now:

<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>

Solution

  • If you're looking to have the 1-column rows span the whole width like this:

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

    Rather than like this:

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

    Then this should be fairly simple to accomplish in TailwindCSS like this:

    <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>