Are “div > p” & “div p” same?

前端 未结 2 1067
眼角桃花
眼角桃花 2020-12-14 03:01

Hey, I\'ve an obvious question.

For code like:

We want to format this text :)

Some

相关标签:
2条回答
  • 2020-12-14 03:31

    Simple:

     div > p
    

    affects only direct children.

     div p
    

    affects grandchildren, grandgrandchildren etc. as well. (Won't make a difference in your example)

    The child selector isn't supported by IE6.

    0 讨论(0)
  • 2020-12-14 03:37

    Pekka has explained it in theory in his answer. Based on his answer, and my answer to another question about the > combinator, I'll provide an illustration, modified to address this question.

    Consider the following block of HTML, and your example CSS selectors. I use a more elaborate example so I can show you the difference between both of your selectors:

    <div>
        <p>The first paragraph.</p>                 <!-- [1] -->
        <blockquote>
            <p>A quotation.</p>                     <!-- [2] -->
        </blockquote>
        <div>
            <p>A paragraph after the quotation.</p> <!-- [3] -->
        </div>
    </div>
    

    Which <p>s are selected by which selectors?

    First off, all of them match div p because they are <p> elements situated anywhere within a <div> element.

    That makes div > p more specific, which begs the next question:

    Which <p>s are selected by div > p?

    1. Selected

      This paragraph <p> is a child, or a direct descendant, of the outermost <div>. That means it's not immediately contained by any other element than a <div>. The hierarchy is as simple as the selector describes, and as such it's selected by div > p.

    2. Not selected

      This <p> is found in a <blockquote> element, and the <blockquote> element is found in the outermost <div>. The hierarchy would thus look like this:

      div > blockquote > p
      

      As the paragraph is directly contained by a blockquote, it's not selected by div > p. However, it can match blockquote > p (in other words, it's a child of the <blockquote>).

    3. Selected

      This paragraph lives in the inner <div>, which is contained by the outer <div>. The hierarchy would look like this:

      div > div > p
      

      It doesn't matter if there are more <div>s nested within each other, or even if the <div>s are contained by other elements. As long as this paragraph is directly contained by its own <div>, it will be selected by div > p.

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