Is there such a thing as an “all inclusive sibling” CSS selector?

后端 未结 4 1862
梦如初夏
梦如初夏 2020-12-01 15:55

My HTML:

Doggies

Froggies

Cupcakes

<
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 16:09

    There is no sibling combinator that looks backward or around, only the adjacent and general sibling combinators that look forward.

    The best you can do is determine a way to limit selection only to these p elements with the same parent, and then select the p children that are :not(.green_guys). If the parent element has an ID of #parent, for example, you can use this selector:

    #parent > p:not(.green_guys) {
        /* selects all 

    children of #parent that are not .green_guys */ }

    However the above will still match your p elements even if none of them have the class. It is currently not possible to select the siblings of an element only given the existence of said element (which is the purpose of a sibling combinator — to establish a relationship between two sibling elements).


    Selectors 4's :has() will hopefully rectify this without the need for a preceding-sibling combinator, resulting in the following solution:

    p:has(~ .green_guys), .green_guys ~ p {
        /* selects all 

    elements that are siblings of .green_guys */ }

    This will not match anything if none of the children of the parent element have the class.

提交回复
热议问题