Possible Duplicate:
Are “div > p” & “div p” same?
Here's the page i'm using as a reference for CSS, please note that i only started learning HTML/CSS this morning.
I'm confused about two of the selectors, quoting the site, the "div p" selector selects all <p> elements inside <div> elements
, and the "div > p" selector selects all <p> elements where the parent is a <div> element
.
What is the difference between those two? Examples where these two selectors can't be used interchangably would be helpful, if possible.
div > p
selects only the <p>
elements that are immediate children of a <div>
.
So:
div > p
will select this paragraph:
<div>
<p>This is a paragraph</p>
</div>
but will not select this paragraph:
<div>
<table>
<tr>
<td>
<p>This will not get selected</p>
</td>
</tr>
</table>
</div>
Selecting all p
tags inside of a div
means ALL p
tags inside of a div
... where as the second means the p
tags that are just one level below a div
.
From The 30 CSS Selectors you Must Memorize #8:
The difference between the standard X Y and X > Y is that the latter will only select direct children. For example, consider the following markup.
Consider this example:
HTML
<div class="one">
<p>asdf</p>
<div>
<p>asdf</p>
</div>
</div>
<div class="two">
<p>asdf</p>
<div>
<p>asdf</p>
</div>
</div>
CSS
div.one p {
margin: 20px;
background-color:#F00;
}
div.two > p {
margin: 20px;
background-color:#0F0;
}
In the first one, both p
tags will be colored red (#F00
) because it selects all p
tags within the div
. In the second, only the first p
tag will be blue (#0F0
) because it only selects direct descendants.
DEMO
div p
is the descendant selector, it will match any p
elements which have a div
higher in their hierarchy. div > p
, which uses the child selector, will only match p
elements whose direct parent is a div
.
http://www.w3.org/TR/CSS2/selector.html#pattern-matching
Case 1: "div p"
implies All the <p>
's will be selected
<div>
<p id=1>
<p id=2>
<p id=3></p>
</p>
</p>
</div>
Case 2: "div > p"
only <p id=1>
will be selected i.e. all p
tags with div
as the immediate parent
div p
will match any p
with an ancestor div
, which need not be its parent. So all these match:
<div><p>Matches</p></div>
<div><form><p>Matches</p></form></div>
<div><section><blockquote><p>Matches</p></blockquote></section></div>
div > p
will only match a p
with a direct parent div
. Like this:
<div><p>Matches</p></div>
(You will note that everything matched by div > p
is also matched by div p
.)