There are several different types of selectors:
Selectors identify the element(s) affected by the CSS rule.
Type selectors specify elements by tag name and affect every instance of that element type. Looking again at a previous example:
This rule specifies that the text of every <p> element should be darkgreen and use a 10-point Verdana font.
Descendant selectors specify elements by ancestry. Each "generation" is separated by a space. For example, the following rule states that <strong> tags within <p> tags should have red text:
With descendant selectors generations can be skipped. In other words, the code above does not require that the <strong> tag is a direct child of the <p> tag.
Child selectors specify a direct parent-child relationship and are indicated by placing a > sign between the two tag names:
In this case only <strong> tags that are direct children of <p> tags are affected.
In HTML, almost all elements can take the class attribute, which assigns a class name to an element. The names given to classes are arbitrary, but should be descriptive of the purpose of the class. In CSS, class selectors begin with a dot. For example, the following rule creates a class called "warning," which makes the text of all elements of that class bold and red:
Following are a couple of examples of elements of the warning class:
If the class selector is preceded by an element name, then that selector only applies to the specified type of element. To illustrate, the following two rules indicate that h1 elements of the class "warning" will be underlined, while p elements of the class "warning" should not be:
Because both rules indicate that the color should be red (#ff0000), this could be rewritten as follows:
Note that you can assign an element any number of classes simply by separating the class names with spaces like this:
As with the class attribute, in HTML, almost all elements can take the id attribute, which is used to uniquely identify an element on the page. In CSS, ID selectors begin with a pound sign (#) and have arbitrary names. The following rule will indent the element with the "maintext" id 20 pixels from the left and right:
Attribute selectors specify elements that contain a specific attribute. They can also specify the value of that attribute.
The following selector affects all links with a target attribute:
The following selector would only affect links whose target attribute is "_blank".
The universal selector is an asterisk (*). It matches every element.
Selectors can share the same declarations by separating them with commas. The following rule will underline all i elements, all elements of the class "warning" and the element with the id of "important."