css - tailwind-css v3 中是否有针对第 n 个 child 的目标?

标签 css reactjs tailwind-css

我总共有 10 个元素,我正在通过它们映射来渲染每个元素。我希望最后一个元素的不透明度最低,第一个元素的不透明度最高。我知道 :first:lasttailwind-css 中,但我想知道是否有办法让我可以定位我的第 8 个或第 9 个 tailwind-css

这是我从一个组件返回的语句:

    {[0,1,2,3,4,5,6,7,8,9].map((item) => (
                            <section
                                key={item}
                                className='last:opacity-20 flex justify-between items-center text-slate-600 bg-white shadow-sm p-5 rounded-xl my-4 cursor-pointer dark:bg-black dark:text-slate-400'
                            >
                                <div className='flex gap-3 items-center'>
                                    <div className='rounded-full w-8 h-8 bg-slate-200'></div>
                                    <p className='w-44 h-4 bg-slate-100'></p>
                                </div>
                                <p className='w-16 h-4 bg-slate-100'></p>
                            </section>
                        ))}

我想降低不透明度,即从第一项到最后一项。

最佳答案

使用 Tailwind v3.2 可以轻松定位 nth-child 匹配变量

// tailwind.config.js
let plugin = require("tailwindcss/plugin");

module.exports = {
  plugins: [
    plugin(function ({ matchVariant, theme }) {
      matchVariant(
        'nth',
        (value) => {
          return `&:nth-child(${value})`;
        },
        {
          values: {
            DEFAULT: 'n', // Default value for `nth:`
            '2n': '2n', // `nth-2n:utility` will generate `:nth-child(2n)` CSS selector
            '3n': '3n',
            '4n': '4n',
            '5n': '5n',
            //... so on if you need
          },
        }
      );
    }),
  ],
}

用法 - 每个 2n 元素都是红色,1st, 6th, 11th, 5n+1 - 绿色,每五个 - 蓝色(它会重叠,但它只是如何从配置或任意变体中使用它的示例)

<ul class="">
  
  <li class="nth-2n:bg-red-400 nth-5n:bg-blue-500 nth-[5n+1]:bg-green-500 p-2">1</li>
  <li class="nth-2n:bg-red-400 nth-5n:bg-blue-500 nth-[5n+1]:bg-green-500 p-2">2</li>
  <li class="nth-2n:bg-red-400 nth-5n:bg-blue-500 nth-[5n+1]:bg-green-500 p-2">3</li>
  <li class="nth-2n:bg-red-400 nth-5n:bg-blue-500 nth-[5n+1]:bg-green-500 p-2">4</li>
  <li class="nth-2n:bg-red-400 nth-5n:bg-blue-500 nth-[5n+1]:bg-green-500 p-2">5</li>
  <li class="nth-2n:bg-red-400 nth-5n:bg-blue-500 nth-[5n+1]:bg-green-500 p-2">6</li>

</ul>

DEMO

对于 3.2 以下的版本,您需要添加 variant addVariant 为每个 nth-child 选择器

关于css - tailwind-css v3 中是否有针对第 n 个 child 的目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74355713/

相关文章:

css - 否定 Tailwind css 中的条件

html - 标题图像覆盖导航功能

javascript - jQuery - 改变滚动条的背景颜色

html - 如何在 Bootstrap 中内联显示两个字段?

javascript - 在 React 中管理数组 prop

html - 为什么当我在类属性中添加 "absolute"时图像消失?

vue.js - 编译的 Tailwind CSS 不包括自定义导入的文件

css - 居中嵌套 float 元素

javascript - React + Three.js 在多个 Canvas 上使用 OrbitControls

reactjs - Firebase 托管的网站不会加载(但会在本地加载)