CSS: list of useful selectors

Selectors

[attribute^="text"]

This selector select all the attributes starting with text.

This is particularly useful if you are using an external css that uses a prefix.

It can be used to apply a different style to internal and external links:

a[href^="https://marco.dev"] {...}

[attribute$="text"]

This selector select all the attributes ending with text.

a[href$=".pdf"]::after { ... pdf icon ...}

[attribute*="text"]

This selector select all the attributes containing text.

[attribute~="text"]

The partial looks for a partial match select all the attributes containing text.

[attribute="text"]

The selector select all the attributes with the following value text.

[attribute]

The selector select all the attributes with the following name attribute.

:only selector

:only-child
Select only the child of an element

:only-of-type
Select only attributes that are children with the defined type.

p:only-of-type selects only <p> that are children of other elements.

:child selector

:first-child
Apply the style to the first child of a series.

:last-child
Apply the style to the last child of a series.

:first-of-type
Apply the style to the first child of the defined type. A document can contain multiple of this attributes.

:last-of-type
Apply the style to the last child of the defined type. If the type is present only 1 time (first and last), it will be selected.
A document can contain multiple of this attributes.

:nth-child()
Apply the style to the element in the selected position.

li:nth-child(even) {...} applies the style to the elements in even position (2, 4, 6, ...)

li:nth-child(odd) {...} applies the style to the elements in odd position (1, 3, 5, ...)

li:nth-child(4n + 2) {...} applies the style to 2nd element and every 4th following

:nth-last-child()

Apply the style to the element in the selected position starting from the last.

Pseudo-classes

:checked
It applies style when the property 'checked' is used in html (checkboxes and radiobuttons)

:disabled
It applies style when the property 'disabled' is used in html

:enabled
It applies style when the property 'disabled' is not used in html

:required
It applies style when the property 'required' is used in html

:optional
It applies the style when the property 'required' is not used in html

target

:target applies the style to the inside link cliked by the user