CSS Selector Cheat Sheet

In CSS, selectors are patterns to identify which DOM elements a style is being applied to. In the following example, h1 and img are selectors for corresponding styles.

1
2
h1 { font-size: 36px; }
img { border: 1px solid #666666; }

There are plenty of selectors available in CSS, here is a cheat sheet of most common ones:

Syntax Example Description
<tag-name> h1

selects all h1 tags in the DOM.

.<class-name> .theme-title

selects all elements with class theme-title.

#<element-id> #nav

selects (all) elements with id nav in the DOM.

[<attr>=<value>] [disabled=true]

selects all element with attribute disabled with
a value of true.

:<state> :hover

selects all elements are being hovered. Other states
are active, focus, link and visitied.

Occasionally, you will be using selectors in combination, such as:

Syntax Description and Examples
<selector-1><selector-2>

selects all elements matched selector-1 AND selector-2.
For example, span.card and div#nav.

<selector-1>,<selector-2>

selects all elements matched selector-1 OR selector-2.
For example, h1,h2,h3 and ol,il.

<selector-1> <selector-2>

selects all elements matched selector-2 that are
decendents of an element matched <selector-1>. For example,
li.product-item a, form#contact input and div.row *.

<selector-1> > <selector-2>

selects all elements matched selector-2 that are direct
children of an element matched <selector-1>. For example,
li.product-item > a and form#contact > input.

<selector-1> + <selector-2>

selects the first element matched selector-2 that is
a direct child of an element matched <selector-1>.
For example, li.product-item > a and form#contact > input.

Even more, you would probably use pseudo-selectors for conditionally selecting elements as below:

Syntax Description and Examples
:first-child

selects the first child of an element, e.g div#nav:first-child.

:last-child

selects the last child of an element, e.g tr.product-item:last-child.

:not(<selector>)

selects all elements that not matched <selector>, e.g a:not(.nav-item).

:nth-child(<pat>)

selects all child elements matched the pat. For example,
#nav:nth-child(odd), #nav:nth-child(even) and #nav:nth-child(3n+1).

::before

adds content before an element, e.g q::before { content: "«" }

::after

adds content after an element, e.g q::after { content: "»" }