Great use of the :not() css selector

I think the :not() css selector is under-utilized.

In most tutorials I see, I don't see this trick being used. In fact, I learned it from Jonas Advanced CSS on Udemy but I been through many tutorials and codebases to know that not many people used it.


Let me show you an example of a great use-case for the :not selector.

Say you are adding margin-right to all the link elements in your nav bar. Usually, you don't want the final element to also have margin-right. Typically, most people do something like this:


a{
  display:inline-block;
  margin-right:3rem; //add margin right
  
  &:last-child{
    margin-right:0rem; //remove margin right from last child
  }
}

You give each element a margin right and then you remove it from the last child.

However, a better way is using the :not() selector. You simply would do:

a{
  display:inline-block;
  
  //give margin right to every element except the last one
  &:not(:last-child){
    margin-right : 3rem;
 } 
}

The second way is a bit shorter and in my opinion more elegant.

Both results, at the end of the day, yield the same result but I feel using :not() is more elegant and clearer as you are saying to add margin-right to all elements except the last one. In contrast, with the first method, you add margin right to all elements just to remove it in the next lines of code.

I hope you find more uses for the :not() pseudoclass!

Make one page websites quickly using my Carrd Templates