Descendant, Child and Adjacent sibling Selectors
Descendant selectors
A descendant selector is made up of two or more selectors separated by white space. A descendant selector of the form "A B" matches when an element B is an arbitrary descendant of some ancestor element A.
For example in our example above
h1 em {color:red;}
Only the descendant <em> of <h1> will follow this rule.
Child selectors
A child selector matches when an element is the child of some element. A child selector is made up of two or more selectors separated by ">".
The following rule sets the style of all P elements that are children of BODY:
body > P { line-height: 1.3 }
the rule applies if your HTML looks like this
<body>
<p> This paragraph will follow the rule declared above</p>
</body>
The following example combines descendant selectors and child selectors:
div ol>li p
It matches a P element that is a descendant of an LI; the LI element must be the child of an OL element; the OL element must be a descendant of a DIV. Notice that the optional white space around the ">" combinator has been left out.
You can even target more specific to the first child of your list by using a pseudo selector :first-child
Adjacent sibling selectors
Adjacent sibling selectors have the following syntax: E1 + E2, where E2 is the subject of the selector. The selector matches if E1 and E2 share the same parent in the document tree and E1 immediately precedes E2, ignoring non-element nodes (such as text nodes and comments).
Thus, the following rule states that when an H1 and an H2 that immediately follows it the margin-top is -5px.
h1 + h2 { margin-top: -5px }
This rule will apply if your html looks like this:
<h1>This is an h1 element</h1>
<h2>This line margin-top will follow the rule</h2>
The following rule is similar to the one in the previous example, except that it adds a class selector. Thus, special formatting only occurs when H1 has :
h1.opener + h2 { margin-top: -5mm }
This rule will apply if your html looks like this:
<h1 class="opener">This is an h1 element</h1>
<h2>This line margin-top will follow the rule</h2>
Notes:
Just think of what the words "child" and "descendant" mean in English:
My daughter is both my child and my descendant
My granddaughter is not my child, but she is my descendant.
Here is the trick, when you have a specific style for the Child selector, you want to write your descendant selector style firs, then write your child selector style after. Think about why?
Just think of what the words "child" and "descendant" mean in English:
My daughter is both my child and my descendant
My granddaughter is not my child, but she is my descendant.
Here is the trick, when you have a specific style for the Child selector, you want to write your descendant selector style firs, then write your child selector style after. Think about why?