Can CSS detect the number of children an element has?

后端 未结 7 2130
猫巷女王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:12

    No. Well, not really. There are a couple of selectors that can get you somewhat close, but probably won't work in your example and don't have the best browser compatibility.

    :only-child

    The :only-child is one of the few true counting selectors in the sense that it's only applied when there is one child of the element's parent. Using your idealized example, it acts like children(1) probably would.

    :nth-child

    The :nth-child selector might actually get you where you want to go depending on what you're really looking to do. If you want to style all elements if there are 8 children, you're out of luck. If, however, you want to apply styles to the 8th and later elements, try this:

    p:nth-child( n + 8 ){
        /* add styles to make it pretty */
    }
    

    Unfortunately, these probably aren't the solutions you're looking for. In the end, you'll probably need to use some Javascript wizardry to apply the styles based on the count - even if you were to use one of these, you'd need to have a hard look at browser compatibility before going with a pure CSS solution.

    W3 CSS3 Spec on pseudo-classes

    EDIT I read your question a little differently - there are a couple other ways to style the parent, not the children. Let me throw a few other selectors your way:

    :empty and :not

    This styles elements that have no children. Not that useful on its own, but when paired with the :not selector, you can style only the elements that have children:

    div:not(:empty) {
        /* We know it has stuff in it! */
    }
    

    You can't count how many children are available with pure CSS here, but it is another interesting selector that lets you do cool things.

提交回复
热议问题