Learn CSS Selectors

As well as HTML elements (e.g. p, h1, etc) you can use various selectors to style your HTML. You should always style by broadest specificity first, to allow for more granular styles as you go down (e.g. by element first, then class, with id used very sparingly as it’s single instance).

Available Selectors

The table below shows the different ways of selecting HTMl to style. They are listed from most general to most specific.

Selector Role Explanation
* Universal selector Targets all HTML elements (or can be set to target children of a specific parent).
.class Selects a HTML class to style. This can help distinguish between different instances of elements (e.g. < p class = ”brand”> vs < p class="general”>). Class selectors override element selectors. CSS .class values can be written separately but can be combined in HTML (see HTML class cribsheet) to apply both styles.
[attribute] selects all elements with a specific attribute (e.g. href) It could style all links without need for a new class instance.
You can also separate out types of attributes depending on their value using element[attribute*=value] (e.g. img[src*=’winter’]{} would only format images with winter in their source links.)
#id to style a unique block of HTML. Cannot have stacked values in HTML as it is unique, so all corresponding style code needs to be in the CSS declaration block and won’t be reused elsewhere on the page. Can be used in combination with a class for both sets of properties but will override element and class selectors.

Chaining Selectors

It is possible to combine selectors in order to add specificity when style elements are valid for mutliple parts of HTML.

Chain Role Explanation
Element.class will style all elements with the listed class. It will not style the same elements with different or no class, nor will it style different elements with the same class.
h1,
.class
will apply styling to BOTH selectors h1 and .class with the same piece of code. No comments.

Descendant Combination

.class child-element = will style all child elements to that class (e.g. list items within a list).

Can also be done with element child-element (ul li) and any other element nested within another (e.g. h5 with nested p).