Syntax - Web Development Podcast

CSS Selectors: A Visual Guide

✨ Here's a visual guide to the most popular CSS selectors.

CSS selectors are patterns used in CSS to select and style HTML elements on a page, allowing us to dictate how styles apply to specific HTML elements.

Along with traditional CSS selectors, we also have pseudo-classes and pseudo-elements. Pseudo-classes allow us to define styles based on an element's state or its relation to other elements. Think of things like hovering over a button or selecting the first item in a list. Pesudo-classes start with a colon character (:).

On the other hand, pseudo-elements give you the power to target and style specific parts of an element, such as its first line or before and after its content. Pseudo-elements start with two colons (::).

This guide serves as your map, detailing and visualizing these essential selectors.

P.S.: You might also want to check out other popular tools and references such as the SVG reference, the color picker and the color palette generator.

* universal selector

Select all elements:

div * {
  background: coral;
}

element element selector

Select element(s):

p {
  background: deeppink;
}

.class class selector

Select all elements with the specified class name:

.my-class {
  background: royalblue;
}

#id ID selector

Select the element with the specified ID:

#my-id {
  background: aquamarine;
}

.class.class-2 multiple selectors

Chain two or more classes or IDs to select the element(s) that have all the specified classes/IDs:

.my-class.special {
  background: royalblue;
}

.class, .class-2 comma combinator

Separate multiple selector declarations using a comma. This makes it easy to apply the same styles to multiple selector declarations:

.item-1, .item-2 {
  background: sandybrown;
}

.class .class-2 descendant selector

Leave a space (descendant combinator) between selectors to select element(s) that are descendant of another element:

.wrapper .card {
  background: lightblue;
}

.class + .class-2 adjacent selector

Use a plus sign (adjacent combinator) to select an element that is a direct sibling to a first element:

.item-1 + div {
  background: yellowgreen;
}

.class > .class-2 child selector

Use a > sign (child combinator) to select element(s) that are direct children to another element:

.wrapper > div {
  background: olive;
}

.class ~ .class-2 general sibling selector

Use a tilde sign (general sibling combinator) to select every element that is preceded by the first element, without having to be a direct sibling to the first element:

.item-1 ~ div {
  background: lightcoral;
}

* + * lobotomized owl

A selector pattern known as the lobotomized owl where all elements that have a preceding sibling are selected. Use it for example to add spacing to elements within a container except for the first element, which has no preceding sibling.

Note that now that we have the :not() pseudo-class, we can select the same elements using :not(:first-child):

* + * {
  background: khaki;
}

[attr] attribute selector

Select element(s) that have a specified attribute:

[data-text] {
  background: deepskyblue;
}

[attr=val] attribute & attribute value

Select element(s) that have the specified attribute and attribute value:

[data-text="hello"] {
  background: lemonchiffon;
}

[attr~=val] attribute & one of the attribute's values

Select element(s) that have the specified attribute with one of it's space-separated values matching the value:

[title~="old"] {
  background: crimson;
}

[attr*=val] attribute & partial value

Select element(s) that have the specified attribute with val being included in the attribute value:

[title*="saur"] {
  background: darkgoldenrod;
}

[attr^=val] attribute & starting value

Select element(s) that have the specified attribute with a value that starts with val:

a[href^='http'] {
  background: Aquamarine;
}
a[href^='#'] {
  background: AntiqueWhite;
}
a[href^='/'] {
  background: LavenderBlush;
}

[attr$=val] attribute & ending value

Select element(s) that have the specified attribute with a value that ends with val:

a[href$='.jpg'], a[href$='.png'] {
  background: greenyellow;
}

:focus focused input element(s)

The :focus pseudo-class targets an element when it receives focus, such as when a user clicks on an input field or navigates to it using the keyboard:

input:focus {
  border: 2px solid deepskyblue;
  background: lightcyan;
  outline: none;
  box-shadow: 0 0 8px rgba(0, 191, 255, 0.5);
}

:checked checked input element(s)

The :checked pseudo-class targets radio buttons, checkboxes, or options in a select element that are currently selected/checked.

In the following example I make use of appearance: none to remove the default styling of the checkbox input, then use the :checked pseudo-class to style the sibling label, while also adding styling on the label when the checkbox is focused:

input[type='checkbox'] {
  /* remove default
     checkbox styles */
  all: unset;
  -webkit-appearance: none;
  appearance: none;
  margin: 0;
}
input[type='checkbox']:checked + label {
  background: mediumseagreen;
}
input[type='checkbox']:focus + label {
  box-shadow: 0 0 0 2px yellow;
}

:disabled disabled input element(s)

The :disabled pseudo-class matches form elements like buttons or text inputs that are disabled:

input[type="text"] {
  padding: 10px;
  border: 2px solid mediumslateblue;
  margin-right: 10px;
}

input[type="text"]:disabled {
  background: lightgray;
  border: 2px solid darkgray;
  color: darkgray;
}

:enabled enabled input element(s)

The :enabled pseudo-class matches form elements that are interactive and can receive input:

input[type="text"] {
  padding: 10px;
  border: 1px solid gray;
  margin-right: 10px;
}

input[type="text"]:enabled {
  background: lightgreen;
  border: 1px solid green;
}

:valid valid input element(s)

The :valid pseudo-class is used to target an input element that has content that matches the requirements as specified by its attributes (like pattern, type, etc.):

input[type="email"]:valid {
  border: 2px solid limegreen;
  background: honeydew;
}

:invalid invalid input element(s)

The :invalid pseudo-class is used to target input elements that have content that doesn't match the requirements:

input[type="email"]:invalid {
  border: 2px solid tomato;
  background: mistyrose;
}

:required required input element(s)

The :required pseudo-class targets input elements that have the required attribute, indicating that they must be filled out before the form can be submitted:

input:required {
  border: 2px dotted orangered;
  background: floralwhite;
  box-shadow: 0 0 10px rgba(255, 69, 0, 0.2);
}

:optional optional input element(s)

The :optional pseudo-class targets input elements that do not have the required attribute, implying that they're not mandatory to fill out:

input:optional {
  border: 2px dotted darkgray;
  background: whitesmoke;
  box-shadow: 0 0 10px rgba(105, 105, 105, 0.2);
}

:first-child first child element

The :first-child pseudo-class targets the first child element within its parent:

div {
  border: 1px dotted gray;
}

div:first-child {
  background: lightblue;
  border-color: deepskyblue;
  border-style: solid;
}
First Child
Second Child
Third Child

:last-child last child element

The :last-child pseudo-class targets the last child element within its parent:

div {
  border: 1px dotted gray;
}

div:last-child {
  background: lightblue;
  border-color: deepskyblue;
  border-style: solid;
}
First Child
Second Child
Last Child

:nth-child nth child element

The :nth-child pseudo-class targets elements based on their position within their parent, allowing for a wide variety of selections.

:nth-child also lets you select elements in patterns:

  • :nth-child(odd) or :nth-child(2n+1) selects every odd-numbered child
  • :nth-child(even) or :nth-child(2n) selects every even-numbered child

The 'n' in the formula is like a counter, letting you target elements in repeating cycles. For instance, :nth-child(3n) would target every third element.

div {
  border: 1px dotted gray;
}

div:nth-child(2) {
  background: lightcoral;
  border-color: darkred;
  border-style: solid;
}
First Child
Second Child
Last Child

:nth-last-child nth child element, counting backwards from last

The :nth-last-child pseudo-class is similar to :nth-child, but it counts from the last child backwards:

div {
  border: 1px dotted gray;
}

div:nth-last-child(2) {
  background: darkorchid;
  border-color: indigo;
  color: white;
  border-style: solid;
}
First Child
Second Child
Third Child
Last Child

:only-child only child of an element

The :only-child pseudo-class targets an element if it's the only child element of its parent:

div {
  border: 1px dotted gray;
}

div:only-child {
  background: lightsalmon;
  border-color: darksalmon;
  border-style: solid;
}
1st Child
Inner child 1
Inner child 2
2nd Child
Only child of '2nd Child'

:first-of-type first element of a type

The :first-of-type pseudo-class targets the first element of its type within its parent:

p, div {
  border: 1px dotted gray;
}

div:first-of-type {
  background: lightyellow;
  border-color: gold;
  color: darkorange;
  border-style: solid;
}

First paragraph

Second paragraph

First div
Second div

:last-of-type last element of a type

The :last-of-type pseudo-class targets the last element of its type within a parent:

p, div {
  border: 1px dotted gray;
}

p:last-of-type {
  background: lightyellow;
  border-color: gold;
  color: darkorange;
  border-style: solid;
}

First paragraph

Second paragraph

First div
Second div

:nth-of-type nth element of a type

The :nth-of-type pseudo-class matches elements based on their type and position among siblings:

p, div {
  border: 1px dotted gray;
}

p:nth-of-type(3) {
  background: lightyellow;
  border-color: gold;
  color: darkorange;
  border-style: solid;
}

First paragraph

Second paragraph

Third paragraph

First div
Second div
Third div

:nth-last-of-type nth element of type, counting backwards

The :nth-last-of-type pseudo-class matches elements based on their type and position among siblings, but counting from the end:

p, div {
  border: 1px dotted gray;
}

div:nth-last-of-type(3) {
  background: lightyellow;
  border-color: gold;
  color: darkorange;
  border-style: solid;
}

First paragraph

Second paragraph

Third paragraph

First div
Second div
Third div

:only-of-type only element of its type

The :only-of-type pseudo-class targets an element that is the only element of its type among its siblings:

p, div {
  border: 1px dotted gray;
}

:only-of-type {
  background: lightyellow;
  border-color: gold;
  color: darkorange;
  border-style: solid;
}

First paragraph

Second paragraph

First div

Paragraph

:target target element selector

The :target pseudo-class selects an element with an ID attribute matching the URL fragment (eg: https://example.com/#fragment).

:target is often used to style sections of a page that are directly linked to, typically used with in-page links:

div:target {
  border: 3px solid deepskyblue;
  background-color: lightcyan;
  transform: scale(1.05);
}
Go to Section 1 Go to Section 2
Section 1 content
Section 2 content

:not() negation pseudo-class

The :not() functional pseudo-class allows you to target elements that do not match a specified selector or condition. It's essentially an exclusion filter:

div:not(.exclude) {
  border: 2px solid royalblue;
  background: aliceblue;
}
This div is targeted
This div has the '.exclude' class
Another targeted div

:has() parent selector

The :has() functional pseudo-class allows to style an element if it contains a certain element or another selector:

div:has(p.special) {
  border: 2px solid darkkhaki;
  background-color: peachpuff;
}

Regular paragraph.

This paragraph has a the '.special' class, so its parent div is styled!

Another regular paragraph.

::before first child pseudo-element

The ::before pseudo-element is used to insert content before the content of an element. It can be used to add decorative content, icons, or other elements that don't need to be in the actual DOM:

.alert::before {
  content: '⚠️ ';
  margin-right: 0.25rem;
}
This is an alert message

::after last child pseudo-element

The ::after pseudo-element is similar to ::before and is used to insert content after the content of an element:

.info::after {
  content: '';
  display: inline-block;
  width: 0.75rem;
  height: 0.75rem;
  border-radius: 35%;
  background: darkseagreen;
  margin-left: 0.35rem;
  rotate: 45deg;
  vertical-align: middle;
}
My message

::first-letter first letter pseudo-element

The ::first-letter pseudo-element is used to style the first letter of a block-level element, allowing for design elements like drop caps:

p::first-letter {
  font-size: 2em;
  font-weight: bold;
  float: left;
  color: crimson;
}

Once upon a time, in a land far, far away, there lived a curious coder on a quest for knowledge.

::first-line first line pseudo-element

The ::first-line pseudo-element is used to style the first line of a block-level element. This allows for typographic effects that can adapt dynamically based on the size of the containing element and the font size:

p::first-line {
  font-weight: bold;
  color: darkslategray;
  text-transform: uppercase;
}

It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness...

::placeholder text input placeholder

The ::placeholder pseudo-element is used to style the placeholder text of form fields like <input> and <textarea>:

input::placeholder {
  font-style: italic;
  color: thistle;
  opacity: 0.7;
}

::selection style highlighted box

The ::selection pseudo-element is used to style the portion of an element that has been highlighted or selected by the user. For instance, when a user clicks and drags to select text, the ::selection pseudo-element can be used to modify the background color, text color, and other styles of that selection:

::selection {
  background-color: gold;
  color: darkblue;
}

Click and drag to select this text to see the custom selection styling in action.

::marker list marker pseudo-element

The ::marker pseudo-element is used to style marker boxes in list items, which typically contain bullets (for unordered lists) or numbers/letters (for ordered lists).

Before the introduction of the ::marker pseudo-element, customizing these markers often required workarounds, but this pseudo-element gives us a bit more control:

li::marker {
  color: LightSeaGreen;
  font-size: 1.5em;
  font-weight: bold;
}
  • Apples 🍎
  • Bananas 🍌
  • Cherries 🍒

More pseudo-classes

Here's some additional pseudo-classes that are available in CSS:

  • :root: Targets the highest-level parent element in a document, typically the <html> element in HTML documents. Useful to define CSS variables that will be available to all elements within the page.
  • :is(): Matches elements that can be one of several selectors, making long selector lists shorter and easier to read. For example, :is(h1, h2, h3) would match any of those three heading elements.
  • :where(): Similar to :is(), but allows for selecting elements based on conditions without affecting the specificity of the selector.
  • :default: Matches UI elements (like radio buttons or checkboxes) that are set to their default selection state.
  • :empty: Selects elements that have no children (including text nodes).
  • :fullscreen: Targets elements that are currently displayed in fullscreen mode.
  • :in-range: Matches form elements with a value that is within the specified range (using attributes like min and max).
  • :out-of-range: Matches form elements with a value that is outside the specified range.
  • :indeterminate: Targets form elements whose state is uncertain, such as a checkbox that's neither checked nor unchecked (often seen in tree-view structures).
  • :read-only: Matches form elements that are not editable by the user, due to the readonly attribute.
  • :read-write: Targets form elements that are editable by the user, implying they are not readonly.
  • :lang(): Matches elements based on their language attribute. E.g., :lang(en) selects elements defined in English.

SVG generators, tools & design resources

cccolor
HEX, RGB & HSL color picker

pppalette
color palette generator

hhhue
curated color palettes

ssshape
SVG blob generator

llline
SVG line generator

dddepth
AI-generated 3D shapes

sssvg
SVG reference

SVG Spinners
How to make them

ffflux
fluid SVG gradients

tttexture
grunge textures

nnnoise
noise texture generator

aaabstract
abstract backgrounds

rrrepeat
repeating SVG shapes

wwwatercolor
watercolor backgrounds

hhholographic
holographic backgrounds

mmmotif
SVG patterns with a 3D feel

gggrain
grainy gradient generator

uuunion
mesh-like gradient generator

nnneon
glowing SVG shapes

ccclaymoji
emoji maker

iiisometric
isometric design builder

sssurf
SVG wave generator

qqquad
generative patterns

dddraw
freehand SVG drawing tool

pppointed
SVG arrow maker

cccloud
cloud SVGs

ssstar
star SVGs

lllove
heart SVGs

bbblurry
blurry background shapes

uuundulate
make some SVG ripples

ccchaos
wild wavy SVG shapes

oooscillate
curvy line patterns

ffflurry
make it rain, SVG-style

cccoil
SVG spiral waves

ssspiral
SVG spiral patterns

cccircular
SVG gradient circle patterns

rrreplicate
SVG line pattern generator

tttwinkle
bursting line patterns

ssscales
gradient SVG patterns

rrrainbow
colorful background patterns

ttten
10 Print-inspired pattern generator

ssscribble
make SVG scribbles

pppixelate
pixel art patterns

sssquiggly
wavy line patterns

ooorganize
SVG grid patterns

vvvortex
spinning circle patterns

gggyrate
spinning geometric patterns

llleaves
organic SVG backgrounds

ggglitch
glitchy shapes

ppperspective
shapes that vanish

sssurface
SVG circles that feel 3D

hhhorizon
Cyberpunk-style backgrounds

sssplatter
make funky SVG shapes

ssspill
generate melting SVGs

ssspot
organic speck patterns

wwwhirl
twisting line patterns

rrreflection
SVG circle patterns

bbburst
confetti generator

dddynamite
decorative SVG shapes

dddivided
split SVG shapes

lllook
fun line icons

dddoodle
hand-drawn doodles

pppsychedelic
psychedelic backgrounds

rrrasterize
convert SVG to PNG

eeencode
encode SVG to Base64

rrready?
support chart for web features

Pick + Convert colors

CCCOLOR

A simple color picker app for Mac, Windows & Linux

Get it here