First-of-type Selector
The ": First-of-type" selector is similar to the ": First-child" selector, where the type of the element is specified , which is used primarily to locate the first child element of a type under a parent element.
Sample Demo:
With the ": First-of-type" selector, locate the first P element in the div container (p is not necessarily the first child element in the container) and set its background color to orange.
HTML code:
<Divclass= "wrapper"> <Div>I'm a block element, I'm the first child element of the. Wrapper</Div> <P>I am a paragraph element, I am not. Wrapper's first child element, but his first paragraph element</P> <P>I am a paragraph element</P> <Div>I'm a block element</Div></Div>
CSS code:
. Wrapper{width:500px;margin:20px Auto;padding:10px;Border:1px solid #ccc;Color:#fff;}. wrapper > Div{background:Green;}. Wrapper > P{background:Blue;}/*I'm going to change the background of the first paragraph to Orange*/. Wrapper > P:first-of-type{background:Orange;}
Demo Result:
Nth-of-type (n) Selector
The :nth-of-type(n)
selector and the selector are :nth-child(n)
very similar, except that it calculates only the child elements of one of the types specified in the parent element. When a child element in an element is not just a child of the same type, it is convenient and useful to use the ": Nth-of-type (N)" selector to locate a child element of some type in the parent element. In the ": Nth-of-type (N)" selector the "n" and ": Nth-child (N)" selectors in the "n" parameter also the same, can be a specific integer , can be an expression , or it can be a keyword .
Sample Demo
With the ": Nth-of-type (2n)" selector, set the background of the number of even segments in the container "div.wrapper" to orange.
HTML code:
<Divclass= "wrapper"> <Div>I am a DIV element</Div> <P>I am a paragraph element</P> <Div>I am a DIV element</Div> <P>I was a paragraph</P> <Div>I am a DIV element</Div> <P>I was a paragraph</P> <Div>I am a DIV element</Div> <P>I was a paragraph</P> <Div>I am a DIV element</Div> <P>I was a paragraph</P> <Div>I am a DIV element</Div> <P>I was a paragraph</P> <Div>I am a DIV element</Div> <P>I was a paragraph</P> <Div>I am a DIV element</Div> <P>I was a paragraph</P></Div>
CSS code:
. Wrapper > P:nth-of-type (2n) { background: orange;}
Demo Result:
"CSS3"---first-of-type selector +nth-of-type (n) Selector