Basic CSS selectors

Selection by tag name

To select one or more elements by their tag, use the tag name directly like a, span, div, header.

Selection by one or more classes

To select one or more elements by one of their classes, use the name of the class preceded by a period “.”.

Example:

.myClass

You can refine your selection by specifying other classes that the element must have, always prefixed with a “.”, attached to the previous class.

.myClass.secondClass

Selection by the presence of an attribute

To select an element or elements that have a certain attribute, you must define the relevant attribute between square brackets “[ ]”.

Example:

a[download]

Selects all links with a download attribute.

Selection by the value of an attribute

To select an element or elements that have a certain attribute, you must define the relevant attribute and its value between square brackets “[ ]”.

Example:

[data-analytics="GMT324-3"]

… or only by the beginning of the value, with the operator “^=”. The following code will return the elements whose value of the attribute data-analytics begins with GMT3:

[data-analytics^="GMT3"]

Selection of an element by its identifier

To select an element by its unique identifier, use the name of the identifier preceded by a hash “#”.

#myId

An identifier is normally unique, so this selector is expected to return only one element. You should therefore not attach several identifiers.

Selector composition

You can compose simple selection modes to refine your selectors. Thus, to select an element by its tag and one of the classes it contains, you can use:

a.myClasse

The identifier being the most accurate selector, it is always at the beginning of the declaration and is often sufficient on its own.

Selection of elements located in other elements

The selector of the parent(s) and child(ren) is separated by a space. The parent(s) can then be direct or indirect parents.

div a

All the <a> elements that have a <div> parent element.

.parent .child

All elements with the child class that have as parent an element with the parent class.

#parent .child

All elements with the child class that are contained in the parent, necessarily unique, with the identifier parent.

#header div span a

Any link that has a <span> parent that itself has a <div>parent, contained in a parent element that have a header identifier.

<div id="header">
    <div>
        <span><strong><a href="#">Link addressed by the selector</a></strong></span>
    </div>
    <span><a href="#">Link not addressed by the selector</a></span>
</div>

Reminder: the child is not necessarily a direct child of the parent.

Back to Table of Contents