【问题标题】:How to give equal space between the items using tailwind css v3如何使用 tailwind css v3 在项目之间提供相等的空间
【发布时间】:2022-11-29 23:54:21
【问题描述】:

我在 next.js 中使用 Tailwind CSS。 我有 8 张不同尺寸的图像,我想为中型和大型设备连续保留 4 个图像,为小型设备连续保留 2 个图像。

我想在一行中的项目之间留出相等的空间,但我希望一行中的第一项位于最左边,而一行中的最后一项位于最右边。 其余项目之间应保持相等的距离。

如何使用 Tailwind CSS 实现此目的?通常在某些条件下,我知道该怎么做,但是有没有办法直接用 Tailwind 来做呢?

来自 API 的 JSON 响应:

     const ourPartners = [
        {
            id: "partner01",
            pic: partner_01
        },
        {
            id: "partner02",
            pic: partner_02,
        },
        {
            id: "partner03",
            pic: partner_03,
        },
        {
            id: "partner04",
            pic: partner_04,
        },
        {
            id: "partner05",
            pic: partner_05,
        },
        {
            id: "partner06",
            pic: partner_06,
        },
        {
            id: "partner07",
            pic: partner_07,
        },
        {
            id: "partner08",
            pic: partner_08,
        }
    ]

我在数组上映射的代码:

      <div className="flex flex-row flex-wrap justify-between items-center">
          {
              ourPartners.map((item, index) => {
                  return (
                      <div className={`md:w-1/4 w-1/2 mb-10 ${(index % 4 !== 0 ? ('flex justify-center') : ('flex justify-start'))}`} key={item.id}>
                          <div className="w-32 object-contain">
                              <Image
                                  alt="partner"
                                  width="auto"
                                  height="auto"
                                  src={item.pic}
                                  quality={100}
                              />
                          </div>
                      </div>
                  )
              })
          }
     </div>

【问题讨论】:

  • 谢谢 @jme11 是的,顺风它有点棘手。我也做了同样的事情,但我使用了获取索引并返回特定项目所需类的函数。我也喜欢你的回答。

标签: css reactjs next.js tailwind-css tailwind-3


【解决方案1】:

编辑:

我实际上也在这里学到了一些新东西。您现在可以在 Tailwind 中使用 nth-child。

const Partners = () => {
  return (
    <div className="grid md:grid-cols-4 grid-cols-2 gap-y-10 justify-between">
      {ourPartners.map((item, index) => {
        return (
          <div
            key={item.id}
            className="odd:justify-self-start even:justify-self-end md:[&:nth-child(4n+2)]:justify-self-center md:[&:nth-child(4n+3)]:justify-self-center"
          >
            <div className="w-32">
              <img alt="partner" width="auto" height="auto" src={item.pic} />
            </div>
          </div>
        );
      })}
    </div>
  );
};

export default Partners;

【讨论】:

  • 谢谢,我试过了,但是如果我使用间隙,那么我必须为多个断点提供不同的间隙值以保持相同的视图