7.2 Selectors
So far in this tutorial we've been using simple selectors called type selectors, such as HTML tags like <h1> and <p> etc. We have also progressed onto using class and id selectors. However, there are also some other useful selectors that can be used in CSS and are worthy of a mention.
The Universal Selector
The asterisk can be used as a universal selector, which is another simple selector, like so:
* { padding:0; margin:0; }
Sometimes called the global whitespace reset, this would have the effect of removing any padding and margins from all HTML elements in a document if required. As well as saving having to state this for every element in the stylesheet, it also saves time dealing with minor cross-browser differences caused by varying default values for these properties.
Combinator Characters
Simple selectors can be chained together using combinator characters. These specify contextual relationships between selectors, such as descendant, child and sibling. Whitespace is also a combinator, for example when used in descendant selectors (but is also permitted around them too).
Descendant Selectors
These are useful for more precise selections. For example, say we had a container div called navigation and only wanted unordered lists inside that div to lose its bullet points (and keep them everywhere else). We can target this precisely like this:
#navigation li {list-style:none;}
Note the combinator character here is a space.
Parent / Child Selectors (not available in IE6)
Unlike descendant selectors that can have many ancestors, a child selector can only have one parent (and vice-versa. Nothing can come between the two. For example, to target any <b> element that is a child of a <div>:
div > em {colour:red;}
Other class="tag"><b> elements that are descendants but not direct children of the <div> will not be targeted. Note the combinator here is a >
Sibling Selectors
Sibling elements share the same parent, and adjacent siblings are right next to each other and share the same parent. The following example would apply a red border to all h2 elements that immediately follow a h1 element that share the same parent:
h1 + h2 {border:1px solid red;}
Note the combinator character here is a +.
Grouping Selectors
Multiple selectors can be grouped in comma-separated lists. The comma is not actually a combinator but just a shorthand way of applying one declaration block to multiple elements (the comma starts an entirely new selector from the beginning). These save marking up multiple instances of CSS. For example:
h1, h2, h3 {color::blue;}
Controlling layout
Where the grouping of elements using class and id selectors along with span and div tags really comes in useful is for controlling the layout of webpages, of which the most common layout is to have a header section at the top, 2 or 3 vertical columns and a footer section at the bottom, something that will be touched upon later in this tutorial.