In-depth understanding of the difference between nth-child and nth-of-type in css3, css3nth-child
In css3, two new selectors can be used to select the corresponding child element under the parent element. One is nth-child and the other is nth-of-type. But what are their differences?
In fact, the difference is very simple: nth-of-type why is it called: nth-of-type? Because it is differentiated by "type. That is to say, ele: nth-of-type (n) indicates the nth ele element under the parent element,
Ele: nth-child (n) indicates the nth element under the parent element and the element is ele. If not, the selection fails. The text is obscure and easy to understand. Here is a small example:
<!DOCTYPE html>The result is as follows ,. demo li: nth-child (2) selects the <li> one </li> node while. demo li: nth-of-type (2) selects the <li> two </li> node. But what if the label is not specified before nth-child and nth-of-type?
.demo :nth-child(2){color: #ff0000;}.demo :nth-of-type(2){color: #00ff00;}
What is the result? Let's look at the html structure:
<ul class="demo"><p>first p</p><li>first li</li><li>second li</li><p>second p</p></ul>
Result:
As shown above, the label type is not specified before, and nth-child (2) is selected as the second element, No matter what label it is. Nth-type-of (2) selects two elements: parent. the second p tag and the second li tag in the demo. When the tag type is not specified, nth-type-of (2) selects the second tag of all types.
We have learned about the basic usage and differences between nth-child and nth-of-type, so we can further develop nth-of-type (n) and nth-child (n) what is n in? N in nth-of-type (n) and nth-child (n) can be numbers, keywords, or formulas.
Number:That is, we will not repeat the use of the above example.
Keywords:Odd, evenOdd, and even are keywords that can be used to match sub-elements whose subscript is an Odd or even number. Note: The subscript of the first sub-element is 1 here, we specify two different background colors for the odd and even p elements:
p:nth-of-type(odd){background:#ff0000;}p:nth-of-type(even){background:#0000ff;}
Formula: or arithmetic expression
Use the formula (an + B ). Description: the length of the cycle. n indicates the counter (starting from 0) and B indicates the offset value.
Here, we specify the background color of all p elements whose subscript is a multiple of 3:
p:nth-of-type(3n+0){background:#ff0000;}
If it is: nth-of-type (4n + 2), The subscript is a multiple of 4 and all the elements of 2 are selected.