Showing posts with label child. Show all posts
Showing posts with label child. Show all posts

Thursday, September 5, 2024

How to use css selectors, :nth-child(n)

css selector :nth-child(n)


1) :nth-child(n)

The :nth-child(n) selector matches every element that is the n-th child of its parent, regardless of the type of element.

element:nth-child(n) { 
  /* styles */ 
}
    

  • Styles the second child if it is a <p> tag


p:nth-child(2) {
  color: blue; 
}  
    

Paragraph 1

Paragraph 2

Span 1

Paragraph 3

Paragraph 4

  • Styles the fourth child if it is a <p> tag


p:nth-child(4) {
  color: red; 
}  
    

Paragraph 1

Paragraph 2

Span 1

Paragraph 3

Paragraph 4

  • Styles the third child if it is a <p> tag

p:nth-child(4) {
  color: red; 
}  
  

Paragraph 1

Paragraph 2

Span 1

Paragraph 3

Paragraph 4

  • Styles the odd-numbered child if it is a <p> tag with :nth-child(odd)
:nth-child(odd) css selector


p:nth-child(odd) {
  background-color: pink; 
}  
  

Paragraph 1

Paragraph 2

Paragraph 3

Paragraph 4

Paragraph 5

Paragraph 6

Paragraph 7

Paragraph 8