This will be the last discussion about CSS selectors in this series. In this article we will discuss the descendant, child and sibling selectors, with numerous code examples. It is the sixth article in our series covering CSS.
Learn CSS, Selectors, Part 3 - The Child Selector (Page 3 of 4 )
The child selector is very similar to the descendant selector, but instead of applying the styling rules if the element has a certain descendant, it will apply the rules if the element has a direct child element. It can be explained better with an example:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <link rel="stylesheet" href="Selectors.css" type="text/css"> <title>CSS Selectors</title> </head> <body> <p><a href="home.html">Home</a> <span>CSS is a wonderful styling language for the web</span></p> <p><span>Using CSS text and font properties to create good looking pages</span> <a href="CSShome.html">CSS Home</a></p> <p><strong><span>This text will not be styled</span></strong></p> </body> </html>
As you can see in the HTML code, there are three <Span> elements. The first <Span> element is a direct child of the first <P> element in the document. The second is a direct child of the second <P> element, but differs from the first <Span> element in just the order -- the first <Span> element exists after the <a> element and the second exists before it. I just wanted to show you that the order is not important with the child Selector. The third <Span> elements exist inside a <Strong> element, which exists inside a <P> element, so this <Span> element is not a direct child of the <P> element. That's why the style will not be applied to it.
The syntax of this selector is very easy. Just use the greater than (>) symbol between the parent and the child. So if <P> is the parent and <Span> is the child you write the CSS child selector as p > span{}. You can remove the white spaces here, so it can look like p>span or p> span -- it doesn't matter. You can read it as the span element has a direct <p> element as the parent or you can read it the other way, the <p> element has a direct <Span> element as the child.
The interesting point about the child selector is that you can use more than one level of nesting. In other words, you can state that a certain element has a direct parent, which is in turn has a specific direct parent, and so on. For example, suppose that you need to set some styling rules to the <Strong> element, which has a direct <Span> element as the parent, which in turn has a direct <P> element as the parent, which in turn as a direct <TD> element as the parent (this tree must exist in this series of direct parent-child relationships). You can use the child selector as follows: