[This is an advanced CSS tutorial. To learn the basics of XHTML and CSS, please view my Web Design Made Simple tutorials.]
It started out with an email discussion with friends, and worked its way into a detailed experiment to grasp how CSS child and adjacent sibling selectors worked. (Important Note: some advanced selectors do not work in IE version 6 or below.)
What is a CSS child? It is a direct descendant of an element.
<div>
<p>This is <em>fun</em></p>
</div>
What is a CSS adjacent sibling? It is an element that follows right after another, as long as they both have the same parent.
<div>
<h1>Heading</h1>
<p>This is fun</p>
<p>This is challenging too</p>
</div>
Now that we have the definitions out of the way, how do the selectors work?
If you want to define a style for a descendant of an element, you would create a CSS rule with two selectors separated by a space.
div em {color:blue;}
The above CSS code would display all em text as blue as long as it was nested somewhere inside a div element.
If you only wanted to define a child, then the greater than special character is used.
div>em {color:blue;}
The above CSS rule would format em text only if it was located directly in the div element. Any em text nested in a paragraph or heading would not display blue.
To define a CSS adjacent selector, the plus sign is used.
h1+p {color:blue;}
The above CSS code will format the first paragraph after any h1 headings as blue.
h1+p+p {color:blue;}
The above CSS code will format the second paragraph after any h1 headings as blue.
The best way to understand CSS is to experiment with it; if you are intimidated to experiment with your own file at first, but if you would like to see an example, I am sharing my child.html file. View source to see the embedded CSS and detailed notes.
Have fun!
Nice Going Debbie. You explained it all in nice easy to understand terminology. This is a hard concept to grasp, and I find some times that books are just to technical to get what they have to say across.
Glad you enjoyed the email conversation.
Hard to grasp is putting it mildly!
I always avoided these advanced selectors because I never wanted to take the time to learn them! You guys made me see the light!
Comment by debbieT on July 18th, 2006This is an excellent explanation of children and descendants, dT! Very concise and an excellent resource.
Comment by Lisa on July 18th, 2006Hi, I never fill these things out…but this made perfect sense of simple matter which the books made into technical drivel. Thanks tons.
Comment by Conrad on October 7th, 2006Very entertaining issue. I haven\’t heard of this one. It will be necessary to visit you on a thicket!
Comment by История Египта on March 18th, 2007