CSS Selectors

Course Content

Grouping Selectors

Although mentioned at National 5 we can group selectors to avoid repeating the same rules. For example if we wanted to style all h1 and h2 elements as blue we could use:

h1,h2 { color: blue ;}

This leads to slightly more efficient code (smaller file sizes) but does improve readability of the CSS rules.

Why we need descendant Selectors

We know how to select and style paragraph elements.

p {color: red;}

But consider the following HTML code and output. 

The problem is that we only want to style the text inside the div. So we could use:

div {color: red;} 

But unfortunately that will style all elements inside the div element (including the list) as can be seen in the screenshot to the right.  Because we styled the whole div tag it has changed the colour of ALL text inside the DIV tag to red. 

Now we could use classes or ID’s but if this was to be scaled over a large number of pages or elements this would not be feasible. So we will use a descendant selector to only select those paragraph elements that are inside a div element (their parent).

Descendant Selectors

We will use the following CSS rule which uses a descendant selector.

div p { color: red; }

This will mean that we are only selecting paragraph elements that are inside a div element. And will give us our desired output in that only the paragraph element inside the div element is styled as can be seen in the screenshot to the right.

Descendant Selector Examples

Further Reading

Although outside the scope of the course, other selectors are detailed here