Can CSS detect the number of children an element has?

后端 未结 7 2132
猫巷女王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 01:15

    Clarification:

    Because of a previous phrasing in the original question, a few SO citizens have raised concerns that this answer could be misleading. Note that, in CSS3, styles cannot be applied to a parent node based on the number of children it has. However, styles can be applied to the children nodes based on the number of siblings they have.


    Original answer:

    Incredibly, this is now possible purely in CSS3.

    /* one item */
    li:first-child:nth-last-child(1) {
    /* -or- li:only-child { */
        width: 100%;
    }
    
    /* two items */
    li:first-child:nth-last-child(2),
    li:first-child:nth-last-child(2) ~ li {
        width: 50%;
    }
    
    /* three items */
    li:first-child:nth-last-child(3),
    li:first-child:nth-last-child(3) ~ li {
        width: 33.3333%;
    }
    
    /* four items */
    li:first-child:nth-last-child(4),
    li:first-child:nth-last-child(4) ~ li {
        width: 25%;
    }
    

    The trick is to select the first child when it's also the nth-from-the-last child. This effectively selects based on the number of siblings.

    Credit for this technique goes to André Luís (discovered) & Lea Verou (refined).

    Don't you just love CSS3?

提交回复
热议问题