Skip to content

CSS Selectors Cheatsheet

getfutureproof-admin edited this page Jul 21, 2020 · 1 revision

The CSS Diner is worth a regular visit to keep this in your fingers!

Select all of tag name

p { /* rules */ }

Select all of class name

.these { /* rules */ }

Select the element with unique id

#this { /* rules */ }

Select everything (use with caution!)

* { /* rules */ }

Grouping selectors Applied to HTML elements that have any of the selectors.

.these, #this { /* rules */ }

Chaining selectors Applied to HTML elements that have all the selectors.

p.these { /* rules */ }

Descendant selectors Applied to any HTML elements where the second selector is inside the first selector (no matter how far nested).

section#info li.name { /* rules */ }

Direct Descendant selectors Applied to any HTML elements where the second selector is inside the first selector as a direct descendant.

section#info > li.name { /* rules */ }

Sibling selectors Applied to any HTML elements where the second selector immidiatly follows the first selector on the same level.

h1 + p { /* rules */ }

Attribute selectors Applied to any HTML elements with the matching attribute.

input[name="surname"] { /* rules */ }

Attribute selectors Applied to any HTML elements with the matching attribute.

a[href="http://google.com/"] { /* rules */ }

You can get more flexible with the assignment here eg:

/* Selects all a tags with an href attribute that starts with 'http' */
a[href^="http"] { /* rules */ }

/* Selects all a tags with an href attribute that ends with '.com' */
a[href$=".com/"] { /* rules */ }

/* Selects all a tags with an href attribute that contains the text 'google' */
a[href*="google"] { /* rules */ }

Psuedo Selectors Applied to any HTML elements in the matching state.

a:hover { /* rules */ }

There are lots of pseudo selectors and css-tricks has a great article running through them all.

BONUS

Psuedo Elements These look very similar the the pseudo selectors but with two colons [::] They come in a variety flavours, two very common ones being ::before and ::after. Pseudo elements can really help clean up your html and avoid any uneccesary 'hacks' or repetition. They are often overlooked and/or forgotten but it's worth spending a little time to check out what is available. W3Schools documentation is good for an overview.

.quote::before { content: '"'; }
.quote::after { content: '"'; }
Clone this wiki locally