我总共有10个项目,我正在映射通过它们来呈现每一个。我希望最后一个元素的不透明度最小,第一个元素的透明度最高。我知道:first和:last在tailwind-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>
))}我想减少opacity下降,即从第一项到最后一项。
发布于 2022-11-08 09:05:04
使用nth-child 顺风v3.2 matchVariant可以很容易地锁定目标
// 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>对于低于3.2的版本,您需要为每个变体选择器添加addVariant
发布于 2022-11-08 05:39:46
以下解决方案可能不使用nth-child,但确实提供了所需的结果:列表项将逐个减少不透明度。
{[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((item) => {
// Generate class name
// Need to config Tailwind as shown later for this to work
const opacity = `opacity-${(10 - item) * 10}`;
// Changed to bg-black here so result is more visible
return (
<section
key={item}
className={`${opacity} flex justify-between items-center text-slate-600 bg-black 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生成所需的类名,需要将以下配置添加到tailwind.config.cjs中
const opacitySafeList = [];
for (i = 1; i < 11; i++) {
opacitySafeList.push(`opacity-${i * 10}`);
}
module.exports = {
content: ["...content of the project"],
// Tell Tailwind to generate these class names which does not exist in content files
safelist: opacitySafeList,
theme: {
extend: {},
},
plugins: [],
};这个特性(安全列表)被Tailwind认为是最后的手段,但是这个问题似乎是一个很好的用例。
https://stackoverflow.com/questions/74355713
复制相似问题