I have a total of 10 items and I am mapping through them to render each one. I want least opacity for last element and highest for first element. I am aware of :first
and :last
in tailwind-css
, but I was wondering if there is way so that I can target lets say my 8th or 9th in tailwind-css
here is my return statement from a component:
{[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>
))}
I want to decrease opacity
going downwards i.e, from first item to last item.
Arbitrary variants can be used for this.
For example, this
<section className="[&:nth-child(8)]:opacity-25">
</section>
gives an opacity of 0.25
to a section element that is an eighth child.
Targeting nth-child
can be easy using Tailwind 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
},
}
);
}),
],
}
Usage - every 2n
element will be red, 1st, 6th, 11th, 5n+1
- green, every fifth - blue (it will overlap but it is just an example how to use it from config or arbitrary variants)
<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
For versions bellow 3.2 you'll need to add variant addVariant
for every nth-child
selector
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With