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

前端 未结 4 839
囚心锁ツ
囚心锁ツ 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:15

    Adjacent sibling selectors X + Y

    Adjacent sibling selectors have the following syntax: E1 + E2, where E2 is the subject of the selector. The selector matches if E1 and E2 share the same parent in the document tree and E1 immediately precedes E2, ignoring non-element nodes (such as text nodes and comments).

    ul + p {
       color: red;
    }
    

    In this example it will select only the element that is immediately preceded by the former element. In this case, only the first paragraph after each ul will have red text.

    ul + p {
        color: red;
    }
    • List Item
    • List Item
    • List Item
    • List Item

    This will be red

    This will be black

    This will be black

    General sibling selectors X ~ Y

    The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent.

    ul ~ p {
       color: red;
    }
    

    This sibling combinator is similar to X + Y, however, it's less strict. While an adjacent selector (ul + p) will only select the first element that is immediately preceded by the former selector, this one is more generalized. It will select, referring to our example above, any p elements, as long as they follow a ul.

    ul ~ p {
      color: red;
    }
    • List Item
      • Child
    • List Item
    • List Item
    • List Item

    This will be red.

    This will be red.

    This will be red.

    This will be red.

    Source

    code.tutsplus

    General sibling selectors MDN

    Adjacent sibling selectors w3

提交回复
热议问题