How to combine pseudo-elements with pseudo-classes?

How to combine pseudo-elements of type :after with pseudo-classes of type :hover and :not ?

 li { margin-bottom: 10px; } li:after { content: ''; display: block; width: 0; height: 3px; background: #009688; transition: width .8s; } li:hover:after { width: 100%; } 
 <ul> <li>first</li> <li>second</li> <li>third</li> <li>forth</li> <li>fifth</li> </ul> 

How can I exclude, for example, the first and third elements in a list from this hover effect?

+6
source share
2 answers

You can associate the :not() pseudo-class with the :nth-child() selector as follows.

 li { margin-bottom: 10px; } li:after { content: ''; display: block; width: 0; height: 3px; background: #009688; transition: width .8s; } li:not(:nth-child(1)):not(:nth-child(3)):hover:after { width: 100%; } 
 <ul> <li>first</li> <li>second</li> <li>third</li> <li>forth</li> <li>fifth</li> </ul> 
+6
source

There are no special rules in combining pseudo-classes and pseudo-elements, except for one rule, which says there can be only one pseudo-element per complex selector and it should appear at the very end . Pseudo-classes can be written in any order - the order of simple selectors does not change the value of the composite selector. Note that a pseudo-element, unlike a pseudo-class, is not a simple selector.

You can write any of

 li:not(:nth-child(1)):not(:nth-child(3)):hover:after 

or

 li:hover:not(:nth-child(1)):not(:nth-child(3)):after 

or

 li:hover:not(:nth-child(3)):not(:nth-child(1)):after 

or, heck, even

 li:not(:nth-child(3)):hover:not(:nth-child(1)):after 

and you will get the same result (provided that the browser is not buggy) until :after , the pseudo-element, appears last (and li , the type selector, appears first).

By convention, most authors prefer to place structural pseudo-classes, such as :nth-child() , before dynamic pseudo-classes, such as :hover . But this is a completely personal preference; it doesn’t matter for the browser.

+6
source

All Articles