60

I recently started to give tailwind.css a try in my Nuxt project. so I needed to use :not(:last-child) pseudo-elements but I don't know how.

  <ul>
    <li
      v-for="(item, index) in items"
      :key="`item-${index}`"
      class="border-solid border-b border-black"
    >
      Item
    </li>
  </ul>

I want to add a border-bottom to all of the <li> except the last one.

I know Tailwind has first & last pseudo-class variant but I can't use them with :not()

daCoda
  • 3,583
  • 5
  • 33
  • 38
Reza Majidi
  • 760
  • 1
  • 7
  • 17

3 Answers3

66

The answer is in the link to last in the docs, that you shared.

Just add last:border-b-0 to all list items, and it will remove the border-bottom if it is the last-child.

<ul>
  <li
    v-for="(item, index) in items"
    :key="`item-${index}`"
    class="border-solid border-b border-black last:border-b-0"
  >
    Item
  </li>
</ul>
Estevan Maito
  • 1,482
  • 1
  • 19
  • 23
  • isn't it a problem with efficiency? because we need to write 2 tailwind classes but in simple CSS we have so much more selector powers. – Reza Majidi Apr 29 '20 at 06:49
  • 2
    1) Give it a try, inspect the list and you will notice that it is only applied to the last item. So no problem with efficiency. 2) That's the whole point with Tailwind: insted of writing CSS, you write classes in HTML. – Estevan Maito Apr 29 '20 at 17:24
  • 1
    also, you need to fix config `variants: { extend: { margin: ['first', 'last'] }, },` – Dmytro Lishtvan May 06 '21 at 14:07
  • 8
    This doesn't work for me. – JohnAllen Oct 31 '21 at 06:40
44

You can use Tailwind arbitrary variants:

<li class="[&:not(:last-child)]:border border-sky-500">Item</li>

This is available since Tailwind v3.

borisdiakur
  • 10,387
  • 7
  • 68
  • 100
2

We could also do this by selecting the index number we want to edit

EXAMPLE: I will change the first one, and all the following should have a style

<div
    v-for="(item, i) in items"
    :key="i"
    :class="{ 'mx-0': i === 0, 'mx-4': i > 0 }"
>
</div>

so the FIRST element has an index from 0, and therefore we will have a margin x 0,

and all of the following would have margin x 4.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Non404
  • 1,130
  • 2
  • 12
  • 22