Search code examples
cssreactjscss-gridgrid-layoutmap-function

CSS Grid layout when mapping through elements


I want to achieve a responsive grid layout that resembles this: Grid Layout

I'm using map() to map through an array of posts coming from the db and display all of them but I'm not sure how to make the grid layout with my code. I currently have a simple grid layout with 3 columns on each row (therefore 3 cards on each row) however I want 3 small cards in the middle column like in the image. In order to do this, I would usually create another nested div and style it appropriately.

Is there a way of targeting some of the posts in the array or would I need to create another function containing some of the posts?

How would I create this grid layout with my code?

 displayPost = (posts) => {
        if (!posts.length) return null;
        return posts.map((post, index) => (
            <Link to={`/post/${post._id}`}>
            <div className="card" key={index}>
            <h3 className="posts-title">{post.title}</h3>
            <p className="posts-body">{post.body}</p>
            <p>{post.date}</p>
            <p>{post.author}</p>
            </div>
            </Link>
        ))
    }


    render() {
        return (
         <div className="grid">
           {this.displayPost(this.state.posts)}
           </div>
        )
    }

}

.grid {
 display: grid;
 grid-template-columns: repeat(3, 1fr);
 grid-gap: 1rem;
 grid-auto-rows: minmax(50px, auto);
}

Solution

  • You can achieve your desired grid layout with this order:

    1 2 3
    1 4 3
    1 5 3
    

    ... with these additional rules:

    .card:nth-child(5n + 1) {
      grid-row-end: span 3;
    }
    
    .card:nth-child(5n + 3) {
      grid-row-end: span 3;
    }
    

    Every group of five elements will repeat this layout.