Showing posts with label CSS. Show all posts
Showing posts with label CSS. Show all posts

Thursday, September 12, 2024

css selector :nth-child(n) , :nth-child(2n), :nth-child(2n+1), :nth-child(3n+1)

 The nth-child pseudo-class in CSS selects elements based on their position in a parent element's child list. The selector you mentioned, :nth-child(3n+1), selects every third child starting from the first one.

First we will see some basic examples

css style with nth child 2n+1



:nth-child(3n+1)

  • 2n: Represents multiples of 2 (e.g., 0, 2, 4, 6, ...).
  • +1: Adds 1 to each multiple, making the sequence start from 1 and select every third element (e.g., 1, 3, 5, 7, ...).

:nth-child(3n+1)

  • 3n: Represents multiples of 3 (e.g., 0, 3, 6, 9, ...).
  • +1: Adds 1 to each multiple, making the sequence start from 1 and select every third element (e.g., 1, 4, 7, 10, ...).

css style with nth child 3n+1


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