DEV Community

Charanjit Chana
Charanjit Chana

Posted on

Do you use the :not() pseudo-class?

Over the past few weeks as I write more and more CSS that I want to be as reusable as possible, I keep coming across scenarios where the first or last element needs to be excluded. Typically for list items, there are a few ways to achieve this thanks to pseudo-classes. Here are two examples:

Override

ul li {
    border-bottom: 1px solid silver;
}
ul li:last-child {
    border-bottom: 0;
}
Enter fullscreen mode Exit fullscreen mode

Using pseudo-classes, override the default for a specific element.

:not()

ul li:not(:last-child) {
    border-bottom: 1px solid silver;
}
Enter fullscreen mode Exit fullscreen mode

Alternatively, use the :not() pseudo-class selector to identify all but the ones you want to target.

What's your preferred way of solving this problem?

For the second option, it's not immediately obvious what the fallback is. This is an extremely simplistic example, but when there are more properties the first one seems to make more sense to me.

Interested to know how others are dealing with the first/last element that needs something just a little different from the others.

Top comments (4)

Collapse
 
rizvanadnan profile image
Adnan Rizvan

I personally use the :not() pseudo occasionally to avoid having to override something unnecessarily or to abstract an element.

Collapse
 
khejit68 profile image
khejit68

I commonly use the same pattern with :first-child and :last-child. I think it's great.

Collapse
 
cchana profile image
Charanjit Chana

I would be surprised if it wasn't the most common approach to be honest, but have you ever considered using :not?

Collapse
 
khejit68 profile image
khejit68

I meant I write the same stuff as your example:

ul li:not(:last-child) {
border-bottom: 1px solid silver;
}