4.2 CSS selectors

Within a CSS rule, the selector specifies which HTML elements will be affected by the rule. There are several ways to specify a CSS selector:

Element selectors:
 
The selector is just the name of an HTML element. All elements of this type in the linked HTML code will be affected by the rule. An example is show below:

a {
    color: white;
}

This rule will apply to all anchor (a) elements within the linked HTML code.

Class selectors:
 
The selector contains a full stop (.) and the part after the full stop describes the name of a class. All elements that have a class attribute with the appropriate value will be affected by the rule. An example is shown below:

p.footer {
    font-style: italic;
}

This rule will apply to any paragraph (p) element that has the attribute class="footer". It will not apply to other p elements. It will not apply to other HTML elements, even if they have the attribute class="footer".

If no HTML element name is specified, the rule will apply to all HTML elements with the appropriate class. An example is shown below:

.figure {
    margin-left: auto;
    margin-right: auto;
}

This rule will apply to any HTML element that has the attribute class="figure".

ID selectors:
 
The selector contains a hash character (#). The rule will apply to all elements that have an appropriate id attribute. This type of rule can be used to control the appearance of exactly one element. An example is shown below:

p#footer {
    font-style: italic;
}

This rule will apply to the paragraph (p) element that has the attribute id="footer". There can only be one such element within a piece of HTML code because the id attribute must be unique for all elements. This means that the HTML element name is redundant and can be left out. The rule below has the same effect as the previous rule:

#footer {
    font-style: italic;
}

Paul Murrell

Creative Commons License
This document is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License.