What are the differences between these two styles :
element1 > element2 {
...
}
and
element1 element2 {
...
}
element1 element2
selects all elements inside element1
Example
<style>
.element1 .element2{
color: #2196F3;
background-color: #FFEB3B;
}
</style>
<div class="element1">
<p class="element2">
As you can see that this paragraph with class `element2` is inside div with class `element1` and so it's catched by css written above.
</p>
</div>
Whereas
element1 > element2
selects every element2
where the parent is a element1
<style>
.element1 > .element2{
color: #2196F3;
background-color: #FFEB3B;
}
</style>
<div class="element1">
<p class="element2">
This paragraph is catched by css above because this paragraph with class `element2` is immediate child of div with class `element1`.
</p>
</div>
<!--no effect-->
<div class="element1">
<div class="middleelement">
<p class="element2">
This paragraph is <strong>NOT</strong> catched by css written above because it's not immediate child of div with class `element1` because class `middleelement` comes in between. To refer to this paragraph, you have to write css as `.element1 > .middleelement > .element2`
</p>
</div>
</div>
element1 > element2
selects all <element2>
elements where the parent is a <element1>
element (see child combinator selector for more information) while element1 element2
selects all <element2>
elements inside <element1>
elements (see descendant selector for more information).
Example:
If you have to following DOM markup (see this JSFiddle):
a
c
b
c
d
c
And you use a c {bg -> red}
(pseudo-code) all c elements will turn red, but if you also use a > c {bg -> blue}
the first c element will turn blue while the other will be red. This is because the a element is the direct parent of the first c element.
>
is the child combinator which signifies a direct child while a space (or >>
) is the descendant combinator, meaning the other element can be anywhere inside the first one.
If you have the following DOM tree
a
b
c
d
then a > c
will match nothing, while a c
will match the c
element.
element1 element2
Selects all elements
inside elements
element1 > element2
Selects all elements
where the parent is a element