我用gridcss,如果数组数是一、二或三,我需要确保元素在中心.

<div className={styles.testWrap}>
  <div className={styles.testGrid}>
    {array.map((value, index) => {
      return (
        <div className={styles.logoBox} key={index}>
          <div
            onClick={() => router.push({ pathname: `./brand/${brand.id}` })}
            className={styles.logoContainer}
          >
            <NextImage src={brand.logoUrl} width={180} height={180} alt="pic" />
          </div>
        </div>
      );
    })}
</div>

CSS

.testWrap {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    background-color: pink;
    .testGrid {
        display: grid;
        width: 100%;
        gap: 24px;
        justify-content: center;
        margin-bottom: 130px;
        @include sm {
            width: fit-content;
            margin: 0 auto;
            grid-template-columns: auto auto;
            grid-template-rows: auto auto;
            margin-bottom: 197px;
        }
        @include md {
            // grid-template-columns: auto auto auto; if array number is three
            // grid-template-columns: auto auto; if array number is two
            // grid-template-columns: auto; if array number is one
            grid-template-columns: params; // How do I get dynamic params over here ?
            justify-content: center;
            grid-gap: 55px;
            width: 100%;
            margin-bottom: 195px;
        }
    }
}

推荐答案

若要根据Reaction组件中数组中的项数动态调整Grid-Template-Columns属性,您可以高效地使用CSS自定义属性(通常称为CSS变量).

我们的 idea 是在Reaction组件中利用JavaScript的字符串操作功能来动态地为网格模板列属性生成所需的值.

以下是一个建议的实现:

<div 
  className={styles.testWrap}
  style={{
    "--dynamic-columns": "auto ".repeat(array.length).trim()
  }}
>
  <div className={styles.testGrid}>
    {/* ...rest of the code */}
  </div>
</div>

在此方法中,我们使用JavaScript的字符串Repeat()方法根据数组长度生成所需的"自动"重复,然后使用trim()修剪前导空格.

.testWrap {
  /*... other styles ...*/
  
  .testGrid {
    /*... other styles ...*/

    @include md {
      grid-template-columns: var(--dynamic-columns);
      /*... other styles ...*/
    }
  }
}

这种方法是高效且可伸缩的.CSS变量的使用确保了动态JS环境和CSS样式之间的无缝集成,为手头的挑战提供了一种优雅的解决方案.

Css相关问答推荐

日期面板未与Angular中的日期控件对齐

正确的`最小/最大宽度`+`非(设备类型)`css媒体查询的语法

CSS Grid我不想要的东西

使用 CSS 定位悬停/弹出 div - 字形浏览器网页

Django:Tailwind 样式不适用于具有小部件属性的模板变量

当弯曲方向设置为列时如何制作等高卡片?

如何在一个父类里面 Select 两个不同的类?

使用 place-content: center 的全宽 CSS 网格项目

使用任意运行时字符串进行 Tailwind CSS 类定位

CSS 仅过渡背景 colored颜色

混合模式粘性位置

:required 或 [required] CSS Select 器

使用border-radius时填充元素之间的空间

CSS Stepper - LI After Overlaying LI Before

有条件地覆盖 CSS 中的 AntD Select 样式

CSS:固定到底部并居中

Highcharts 图表选项 backgroundColor:'transparent' 在 IE 8 上显示黑色

Angular 动画的目的是什么?

了解 Bootstrap 3 中的网格类( col-sm-# 和 col-lg-# )

如何在 CSS 中给出背景图像路径?