Difference between div-div and div: not (: first-of-type)?

Is there any difference between div~div and div:not(:first-of-type) ? Besides IE6, regardless of errors, are there any cases where they will do different things?

+6
source share
1 answer

There is no difference in terms of matching elements. Any div that follows some other div inside the same parent is not necessarily the first div element inside its parent.

If the sibling selector was + , not ~ , then div+div has the added condition that the next element should appear immediately after the previous element. This does not apply to ~ - any number of brothers and sisters of any other kind may appear between them.

If the pseudo-class was :first-child , not :first-of-type , then div:not(:first-child) would still match div:first-of-type if the first div inside its parent is not its first a descendant.

Here is an illustration:

 <section> <div></div> <!-- div:first-child or div:first-of-type --> <div></div> <!-- div+div or div~div or div:nth-of-type(2) --> <p></p> <div></div> <!-- div+p+div or div~div or div:nth-of-type(3), but not div+div --> </section> <section> <h1></h1> <!-- h1:first-child --> <div></div> <!-- div:first-of-type or div:nth-child(2) --> <div></div> <!-- div~div or div:nth-of-type(2) or div:nth-child(3) --> </section> 

There is a difference in terms of specificity . If you have CSS rules with two selectors matching the same elements, then div:not(:first-of-type) will take precedence because of the :first-of-type pseudo :first-of-type . Please note that :not() not taken into account - only its argument is considered.

Here is another illustration:

 div { float: left; width: 50px; height: 50px; margin: 5px; border: 1px solid red; } /* 1 pseudo-class, 1 type -> specificity = 0-1-1 */ div:not(:first-of-type) { border-color: green; } /* 2 types -> specificity = 0-0-2 */ div ~ div { border-color: blue; } 
 <section> <div></div> <div></div> <div></div> </section> 
+5
source

Source: https://habr.com/ru/post/978856/


All Articles