【问题标题】:CSS Grid layout when mapping through elements通过元素映射时的 CSS 网格布局
【发布时间】:2020-07-17 18:56:26
【问题描述】:

我想实现类似这样的响应式网格布局:

我正在使用 map() 映射来自数据库的一组帖子并显示所有帖子,但我不确定如何使用我的代码进行网格布局。我目前有一个简单的网格布局,每行有 3 列(因此每行有 3 张卡片),但是我希望中间列有 3 张小卡片,如图所示。为了做到这一点,我通常会创建另一个嵌套的 div 并适当地设置它的样式。

有没有办法定位数组中的一些帖子,还是我需要创建另一个包含一些帖子的函数?

如何使用我的代码创建此网格布局?

 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);
}

【问题讨论】:

标签: css reactjs css-grid grid-layout map-function


【解决方案1】:

您可以通过以下顺序实现您想要的网格布局:

1 2 3
1 4 3
1 5 3

...带有这些附加规则:

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

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

每组五个元素将重复此布局。

【讨论】:

    猜你喜欢
    • 2021-05-19
    • 2021-01-30
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    相关资源
    最近更新 更多