Narrowing a selection
In this lesson you will learn some ways to make your selection more specific.
- Combining selector types
- Selecting descendants of other elements
Keep your selectors as 'general' as possible
Before getting carried away, you should be aware that it is good practice to keep your selectors as 'general' as possible. In other words, only make them as specific as necessary.
Combining selector types
One way to narrow a selection is to combine selector types. For example, you can narrow your selection by selecting the elements of a certain type that belong to a particular class. This is done by combining the element name with the class name, as shown below. Note the format: There is no space between the element name and the class name (they are 'chained').
(selects <div> elements of the class 'classname')
Selecting descendants of other elements
Another way to narrow your selection is to select elements that are descendants of another element. Note that in this case there is a space. Also note the order – the child on the right, the parent on the left, so read it from right to left.
(elements of class 'classname' that are descendants of element with ID of 'idname') .classname div
(<div> elements that are descendants of elements of 'classname' class)
Here are some examples to illustrate the content of this lesson:
(all <p> elements i.e. paragraphs) p.classname
(<p> elements of class 'classname') .classname
(everything of the class 'classname') #idname
(the element with the id of 'idname') #idname p.classname
(<p> elements of the class 'classname' that are descendants of element with ID of 'idname')
You can achieve an awful lot using the selectors above, but there's no need to limit yourself to them. CSS offers a multitude of other ways to narrow your selection. When you get some confidence you may wish to explore these other ways. Have a look at the complete list at the W3 Schools site.