The difference between Nth-child and Nth-of-type in CSS3 is actually very simple:: Nth-of-type Why to call: Nth-of-type? Because it is differentiated by "type". That is, Ele:nth-of-type (n) refers to the nth ele element under the parent element, while Ele:nth-child (n) refers to the nth element under the parent element and the element is ele, if not, the selection fails.
The text sounds rather obscure and understandable, with a small example attached here:
<! DOCTYPE html>
The results are as follows:
In this example, the. Demo Li:nth-child (2) selects the <li>one</li> node, and the. Demo Li:nth-of-type (2) selects the <li>two</li> Node.
But what if I don't specify a label before Nth-child and Nth-of-type?
. Demo:nth-child (2) {color: #ff0000;}. Demo:nth-of-type (2) {color: #00ff00;}
What would be the result, 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>
Results:
As seen above, before they do not specify a label type: Nth-child (2) The check is still the second element, no matter what label it is. Instead: nth-type-of (2) selected two elements, which are the parent. The second P tag and the second Li tag in the demo, so that when the label type is not specified, nth-type-of (2) selects the second of all type labels.
We have already understood the basic use and difference of nth-child and nth-of-type, so what is the further n of Nth-of-type (n) and Nth-child (n)?
N in Nth-of-type (n) and Nth-child (n) can be numbers, keywords, or formulas. Figures: that is, the use of the above example, do not repeat. Key words: ODD, even
ODD and even are keywords that can be used to match sub-elements with an odd or even number subscript
Note: The subscript for the first child 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;}
A formula: or an arithmetic expression.
Use the formula (an + B). Description: Indicates the length of the period, N is the counter (starting at 0), and B is the offset value.
Here, we specify the background color of all p elements that have a multiple of 3 in the subscript:
P:nth-of-type (3n+0) {background: #ff0000;}
if: Nth-of-type (4n+2) is to select the subscript is a multiple of 4 plus 2 of all elements