Skip to content

10. Other Selectors

martin@mustbebuilt.co.uk edited this page Sep 3, 2024 · 2 revisions

Multiple Selectors

Sometimes we want rules to apply in more than one circumstance. This is achieved by separating the selectors with a comma. The following can be used to apply the same font-family property to all <h1>, <h2> and <h3> elements.

Add the following to apply the same font styling to multiple elements.

h1,h2,h3 {
    font-family: Arial, Helvetica, sans-serif;
}

More Specific Selectors

Class selectors can be used with HTML selectors to define specific rules that will only be applied to a tag with the class applied. For example, the following rule will only apply to <p> elements that have the class attribute set to maintext.

p.maintext{
    color: #FF0000;
}

Any other combination of HTML element with the maintext` class will not recognize the rule.

Thus the <li> tag below, even though it has the class attribute, will not pick up the p.maintext rule.

<li class="maintext">Paragraph Two</li>

Combinators

HTML selectors can also be use variables combination techniques.

Descendant Selector (space)

The following rule is only applied when a <strong> tag is a child of a <p> tag.

p strong{
    color: #FF0000;
}

White spacing is used to separate the elements. In the above example <p> is the parent of <strong>.

Child Selector (>)

To select the children of a specific element use >.

p > strong{
    color: #FF0000;
}

The <strong> tag is only styled if it is a child of a <p> tag ie:

<p><strong>Made Red</strong></p>

Tip

The above is not an exhaustive list. Once you are comfortable with the above you could investigate additional css selectors for more options.

Clone this wiki locally