loading...

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

cchana profile image Charanjit Chana 惻1 min read

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;
}

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

:not()

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

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.

Posted on by:

cchana profile

Charanjit Chana

@cchana

Full stack developer / UI/UX architect with a love for lightweight HTML and CSS (using SASS). Progressive Enhancement FTW!

Discussion

markdown guide
 

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

 

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

 

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

 

I meant I write the same stuff as your example:

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