Roots
Back

Combining Classes And IDs

Groupings

If there are certain style traits that you want to apply to different parts of your website, you can group the classes or IDs of those elements together in your CSS file. To do this write them as a list separated by commas;

h1, h2, h3, h4 { color: #0000FF; }


In the above example the <h1> through to <h4> elements will all have blue text.

Contextual Selectors

Contextual selectors are a way of applying a style to an element only when it is nested within certain other elements. To do this write the selectors as a list separated by spaces;

Example 1: p b { color: #0000FF; }
Example 2: .myClass b { color: #0000FF; }
Example 3: #myID b { color: #0000FF; }

Example 1 styles any text that is in <b> tags, and also in <p> tags - either directly within them or inside other tags, inside the <p> tags.
Example 2 styles any text that is in <b> tags, and also in any tag with the class set to myClass - either directly or indirectly.
Example 2 styles any text that is in <b> tags, and also in any tag with the ID set to myID - either directly or indirectly.

If you want to style text in a tag which is a direct descendant of another, use the following code;

p > b { color: #0000FF; }

All <b> tags that are directly inside <p> tags will be styled.

You can also style an element which directly follows another, both being inside the same parent tag;

p + b { color: #0000FF; }

All <b> tags that directly follow <p> tags, inside some other element, will be styled.

Grouping Contextual Selectors

Contextual selectors can be grouped together in the same way as normal;

.myClass b, #myID b { color: #0000FF; }