CSS nth-child for greater than and less than

前端 未结 6 1569
萌比男神i
萌比男神i 2021-01-31 13:24

In my HTML I have,

6条回答
  •  青春惊慌失措
    2021-01-31 14:22

    :nth-child() doesn't work on classes, it looks for the element itself. You'd need to wrap the .container divs by a wrapper and use the following:

    .wrapper div:nth-child(n+3) {
       /* put your styles here... */
    }
    

    Working Demo.

    Clarifying on :nth-child()

    Using .container:nth-child(n+3) may or may not work. Because, :nth-child() pseudo-class represents nth child element matching the selector (.container in this case).

    If the .container element isn't the nth-child of its parent, it won't be selected.

    From the Spec:

    The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element.

    Consider this example:

    1st
    2nd
    3rd
    4th
    5th
    6th
    7th
    8th
    9th

    In this case, .container:nth-child(2) won't select the 2nd div.container element (which has 5th content). Because that element is not the 2nd child of its parent, in parent's children tree.

    Also, .container:nth-child(n+3) will select all the div.container elements because n starts from 0 for the first element in the parent's children tree, and the first div.container is the 4th child of its parent.

    n starts from 0
    
    n = 0: (0 + 3) = 3 => 3rd element
    n = 1: (1 + 3) = 4 => 4th element
    n = 2: (2 + 3) = 5 => 5th element
    ...
    

    Hence div.container:nth-child(n+3) represents all the 3rd, 4th, 5th, ... child elements matching div.container selector.

    Online Demo.

提交回复
热议问题