Can CSS detect the number of children an element has?

后端 未结 7 2138
猫巷女王i
猫巷女王i 2020-11-22 00:52

I\'m probably answering my own question, but I\'m extremely curious.

I know that CSS can select individual children of a parent, but is there support to style the ch

7条回答
  •  一生所求
    2020-11-22 00:56

    NOTE: This solution will return the children of sets of certain lengths, not the parent element as you have asked. Hopefully, it's still useful.

    Andre Luis came up with a method: http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/ Unfortunately, it only works in IE9 and above.

    Essentially, you combine :nth-child() with other pseudo classes that deal with the position of an element. This approach allows you to specify elements from sets of elements with specific lengths.

    For instance :nth-child(1):nth-last-child(3) matches the first element in a set while also being the 3rd element from the end of the set. This does two things: guarantees that the set only has three elements and that we have the first of the three. To specify the second element of the three element set, we'd use :nth-child(2):nth-last-child(2).


    Example 1 - Select all list elements if set has three elements:

    li:nth-child(1):nth-last-child(3),
    li:nth-child(2):nth-last-child(2),
    li:nth-child(3):nth-last-child(1) {
        width: 33.3333%;
    }
    

    Example 1 alternative from Lea Verou:

    li:first-child:nth-last-child(3),
    li:first-child:nth-last-child(3) ~ li {
        width: 33.3333%;
    }
    


    Example 2 - target last element of set with three list elements:

    li:nth-child(3):last-child {
        /* I'm the last of three */
    }
    

    Example 2 alternative:

    li:nth-child(3):nth-last-child(1) {
        /* I'm the last of three */
    }
    


    Example 3 - target second element of set with four list elements:

    li:nth-child(2):nth-last-child(3) {
        /* I'm the second of four */
    }
    

提交回复
热议问题