문제

Hey, I've an obvious question.

For code like:

<div>
     <p>We want to format this text :)</p>
</div>

Some people use selector like:

div > p {
     something
}

And others:

div p {
     something
}

What's the difference in this case? In my opinion - none?

And by the way, isn't the descendant item always a child?! What's the difference between the two? I'm reading w3.org but can't get it :)

Thank you!

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top