What is the logic behind sibling selectors * + * and * ~ *?

前端 未结 3 932
难免孤独
难免孤独 2020-12-30 23:56

For this question I\'m using the following markup:


    

1

相关标签:
3条回答
  • 2020-12-31 00:34

    They are not applied to the first paragraph actually. To demonstrate this, let's change the stylesheet a bit:

    * + *    { border-right: solid red }
    * ~ *    { border-left: solid black; }
    

    demo

    fiddle

    They are both applied to the "body" element which is in fact preceded by "head".

    0 讨论(0)
  • 2020-12-31 00:39

    * + * Styles any element that is an immediate sibling of any element starting from the document root - Since the <head> is actually an immediate preceding sibling of the body (despite not being visible in your code) this selector targets the body and the last two paragraphs, since the first paragraph isn't immediately following another sibling element. All three paragraphs happened to be underlined due to the nature of text-decoration on block-level descendants in the normal flow.

    * ~ * This is basically the same thing as above, except using the general sibling combinator .. it styles downstream sibling element(s) that appear after the <head> regardless of whether they're immediate siblings or not. Since the <body> is the only sibling, this has the same effect as the above selector. The first paragraph is italicized due to inheritance.

    p ~ * selects a sibling element that is following a <p> which in your example is the last two paragraphs. p + * styles any element that is immediate sibling of a paragraph, which would also be the last two <p> elements.

    0 讨论(0)
  • 2020-12-31 00:47

    That's an error in your test case. As you would expect, none of the selectors match the first paragraph, but the styling from the body cascades to the paragraphs!

    Both * + * and * ~ * match body as it is preceded by a head tag. Thus, it receives text-decoration:underline and font-style:italic. That explains why all of the paragraphs are both underlined and italicised.

    0 讨论(0)
提交回复
热议问题