first: and last: , even: and odd: don't work on "tailwindcss": "^3.1.6"

8.6k views Asked by At

so I'm learning tailwind CSS but when I arrived at variants I got stuck

so when I use first: and last: only first works and it gets applied to all my list elements, it is supposed to work only to the first one, its the same for even and odd, please help me out

1

<ol class=" first:bg-green-500 last:bg-black">
    <li>Lorem ipsum dolor sit amet.</li>
    <li>Lorem ipsum dolor sit amet.</li>
    <li>Lorem ipsum dolor sit amet.</li>
    <li>Lorem ipsum dolor sit amet.</li>
    <li>Lorem ipsum dolor sit amet.</li>
    <li>Lorem ipsum dolor sit amet.</li>
   </ol>

2

There are 2 answers

5
Ihar Aliakseyenka On BEST ANSWER

This classes should be applied on child elements, not parent

<ul class="">
  <li class="first:bg-green-500 last:bg-black">Lorem ipsum dolor sit amet.</li>
  <li class="first:bg-green-500 last:bg-black">Lorem ipsum dolor sit amet.</li>
  <li class="first:bg-green-500 last:bg-black">Lorem ipsum dolor sit amet.</li>
  <li class="first:bg-green-500 last:bg-black">Lorem ipsum dolor sit amet.</li>
  <li class="first:bg-green-500 last:bg-black">Lorem ipsum dolor sit amet.</li>
  <li class="first:bg-green-500 last:bg-black">Lorem ipsum dolor sit amet.</li>
</ul>

DEMO

In case you HAVE control over every element it is better to change style on exact element

<ul class="">
  <li class="bg-green-500">Lorem ipsum dolor sit amet.</li>
  <li class="">Lorem ipsum dolor sit amet.</li>
  <li class="">Lorem ipsum dolor sit amet.</li>
  <li class="">Lorem ipsum dolor sit amet.</li>
  <li class="">Lorem ipsum dolor sit amet.</li>
  <li class="bg-black">Lorem ipsum dolor sit amet.</li>
</ul>

This utility class is very useful when working with loops. For example

<ul class="">
    <!-- Some Loop -->
  @foreach($els as $el)
    <li class="first:bg-green-500 last:bg-black">First will be green, last will be black.</li>
  @endforeach
</ul>
0
Sanan Ali On

If you don't like the accepted answer and want to apply it to the parent element instead of all the children, here is another way to do the same in TailwindCSS. Here is the demo link on tailwind playground.

<ul class="[&>*:last-child]:text-blue-600 [&>*:last-child]:font-bold ">
        <li>First List Item</li>
        <li>Second List Item</li>
        <li>Third List Item</li>
        <li>Fourth List Item</li>
        <li>Fifth List Item</li>
        <li>Last List Item</li>
    </ul>