How to use :not() in tailwind.css
Asked Answered
B

5

87

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()

Buchholz answered 27/4, 2020 at 9:17 Comment(0)
S
104

You can use Tailwind arbitrary variants:

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

This is available since Tailwind v3.

Spireme answered 15/11, 2022 at 12:50 Comment(2)
That saves having to write a pluginMalcolm
This one is more accurate <li class="[&_div:not(:last-child)]:border-r-2 [&_div]:border-red-500">Item</li>Talaria
C
88

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>
Coefficient answered 28/4, 2020 at 22:29 Comment(4)
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.Buchholz
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.Coefficient
also, you need to fix config variants: { extend: { margin: ['first', 'last'] }, },Muna
This doesn't work for me.Tights
Y
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.

Ye answered 16/9, 2020 at 11:10 Comment(0)
A
0

You can change the display layout to use a grid instead of the flex and add some row gap space.

  <div className="grid grid-cols-1 gap-y-4">
      ...
  </div>
Aloysia answered 26/4, 2024 at 8:28 Comment(0)
J
0

Another cool thing you can do is also select pseudo-classes!

The intuitive solution will not work:

[:not(:group-hover)]:your-style

You need to apply it like this:

group-[:not(:hover)]:your-style
Jauch answered 13/5, 2024 at 21:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.