Difference between the selectors div + p (plus) and div ~ p (tilde)

前端 未结 4 843
囚心锁ツ
囚心锁ツ 2020-11-29 21:46

The way that w3schools phrases it, they sound the same.

W3Schools\' CSS reference

div + p
Selects all

4条回答
  •  一个人的身影
    2020-11-29 22:05

    If a

    element is immediately after a

    element, doesn't that mean that the

    element is preceded by a

    element?

    This is correct. In other words, div + p is a proper subset of div ~ p — anything matched by the former is also matched by the latter, by necessity.

    The difference between + and ~ is that ~ matches all following siblings regardless of their proximity from the first element, as long as they both share the same parent.

    Both of these points are most succinctly illustrated with a single example, where each rule applies a different property. Notice that the one p that immediately follows the div has both rules applied:

    div + p {
        color: red;
    }
    
    div ~ p {
        background-color: yellow;
    }
    Div

    Paragraph

    Paragraph

    Paragraph

    No div

    Paragraph

    Paragraph

    Paragraph

    Anyhow, I'm looking for a selector where I can select an element that is place immediately before a given element.

    Unfortunately, there isn't one yet.

提交回复
热议问题