DEV Community

Cover image for Learn to say :not()
Ustariz Enzo
Ustariz Enzo

Posted on • Updated on

Learn to say :not()

Hi everyone, Enzo here !

The :not() selector can be really handy, but there is not much documentation about it.

Here are some useful cases.

1.The border trick

Let's say you have an horizontal grid, and you want to separate each cell with a border-right.

.item-grid{
    border-right: 2px solid #000;
}
Enter fullscreen mode Exit fullscreen mode

border

Each cell has a border-right, great, but since the overall grid has borders too, you end up with 2 borders combined on the last cell !

Here is the trick with :not() :

/* :last-child or :last-of-type work */

.item-grid:not(:last-of-type) {
    border-right: 1px solid #000;
}

Enter fullscreen mode Exit fullscreen mode

Hocus pocus ! Now it's clean.

border clean

2.Multiple :not()

We can go crazy by chaining them, like this :

.item-grid:not(:nth-child(1)):not(:nth-child(3)){
    background: #000;
}
Enter fullscreen mode Exit fullscreen mode

It permits us to remove some square from the selection, instead of rewriting multiple selectors :

Multiple square

But chaining :not() can looks ugly and being hard to understand, so be careful with that one.

3.The article.

Let say you have a container, with a lot of elements inside, like an article.

 <article>
     <h2>Lorem ipsum dolor sit amet.</h2>
     <hr>
     <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet consectetur veritatis recusandae vitae voluptates sunt est, magni harum ex obcaecati.</p>
     <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut magni fuga eum eius, natus iure.</p>
     <a href="#">Lorem, ipsum dolor.</a>
 </article>
Enter fullscreen mode Exit fullscreen mode

We often need to apply properties to multiple elements inside a container, but with some exceptions.
We can do it with :not().

Applying padding to everything but the HR :

article *:not(hr){
    padding: 10px 0;
}
Enter fullscreen mode Exit fullscreen mode

Font-family to all the text except the link :

article *:not(a){
    font-family: Arial, Helvetica, sans-serif;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks !

You can find me on YouTube, talking about web development(warning, it's in French!🥖🥐🍷 ).
I plan to start an English channel too, I just need few weeks to work on my bloody accent.

YT : https://www.youtube.com/c/TheWebSchool

Take care, and see you next time. ✒️

Top comments (0)