-2
element element     div p   Selects all <p> elements inside <div> elements  1
element>element     div > p     Selects all <p> elements where the parent is a <div> element    2
element+element     div + p     Selects all <p> elements that are placed immediately after <div> elements   2
element1~element2   p ~ ul  Selects every <ul> element that are preceded by a <p> element

When I see the course of w3schools, it explain those four selectors by that, but I am very confusing for the explain especially the first term and the second term, it looks like the same thing, anybody can give simple examples to explain what's different for those four selectors?

Hsiu Chuan Tsao
  • 1,036
  • 1
  • 11
  • 21
  • You have the documentation available to you. Try using the W3C for detailed explanations of [what each combinator does](https://www.w3.org/TR/css3-selectors/#combinators). The full list of selectors can be found here: https://www.w3.org/TR/css3-selectors/#selectors. – Joseph Marikle Apr 19 '17 at 13:21
  • 1
    Although W3Schools have improved, you still can't beat MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors – BenM Apr 19 '17 at 13:22
  • Check [the **explanation** here](http://stackoverflow.com/a/43325635/3669624). – cнŝdk Apr 19 '17 at 13:23

2 Answers2

0

Take this snippet for example:

<div>
    <p>Something</p>
    <section>
        <p>This is inside</p>
    </section>
</div>
  1. div p -> Both 'Something' and 'This is inside' will be selected.
  2. div > p -> Only 'Something` will be selected.

Another snippet

<div>
</div>
<p>Something</p>
<p>This is inside</p>
  1. div + p : Only 'Something' will be selected.[Only first element]
  2. div ~ p : Will select both the p elements after the div
Jones Joseph
  • 3,856
  • 1
  • 19
  • 37
0

div > p does match

<div>
    <p>foo</p>
</div>

but it does not match

<div>
    <footer>
        <p>Foo</p>
    </footer>
</div>

That's the difference between 'elements inside' (second one) and 'elements where the parent is' (first one). The parent of the <p> in the second example is the footer, so footer > p would match and so does div p.

div + p would match the p for

<section>
    <div></div>
    <p></p>
</section>

but not for

<section>
    <div></div>
    <span></span>
    <p></p>
</section>

since the <p> is not immediately after. In this example, div ~ p would match since this selector only requires the p to follow the div on the same level of the DOM tree.

SVSchmidt
  • 5,336
  • 2
  • 17
  • 33