CSS Selectors

Structural pseudo classes

p:first-child First child
p:last-child Last child
p:first-of-type First of some type
p:last-of-type Last of some type
p:nth-child(2) Second child of its parent
p:nth-child(3n42) Nth-child (an + b) formula
p:nth-last-child(2) Second child from behind
p:nth-of-type(2) Second p of its parent
p:nth-last-of-type(2) …from behind
p:only-of-type Unique of its parent
p:only-child Only child of its parent

Input pseudo classes

input:checked Checked inputs
input:disabled Disabled inputs
input:enabled Enabled inputs
input:focus Input has focus
input:in-range Value in range
input:out-of-range Input value out of range
input:valid Input with valid value
input:invalid Input with invalid value
input:optional No required attribute
input:required Input with required attribute
input:read-only With readonly attribute
input:read-write No readonly attribute
input:indeterminate With indeterminate state

Pseudo classes

p::after Add content after p
p::before Add content before p
p::first-letter First letter in p
p::first-line First line in p
::selection Selected by user
::placeholder Placeholder attribute
:root Documents root element
:target Highlight active anchor
div:empty Element with no children
p:lang(en) P with en language attribute
:not(span) Element that's not a span

User action pseudo classes

a:link Link in normal state
a:active Link in clicked state
a:hover Link with mouse over it
a:visited Visited link

Attribute selectors

a[target] With a target attribute
a[target="_blank"] Open in new tab
a[href^="/index"] Starts with /index
[class|="chair"] Starts with chair
[class*="chair"] containing chair
[title~="chair"] Contains the word chair
a[href$=".doc"] Ends with .doc
[type="button"] Specified type
See also: Attribute selectors

Combinators

Selector Description
div.classname Div with certain classname
div#idname Div with certain ID
div p Paragraphs inside divs
div > p All p tagsone level deep in div
div + p P tags immediately after div
div ~ p P tags preceded by div
See also: Adjacent / Sibling / Child selectors

Basic

* All elements
div All div tags
.classname All elements with class
#idname Element with ID
div,p All divs and paragraphs
#idname * All elements inside #idname
See also: Type / Class / ID / Universal selectors

Examples

#Groups Selector

h1, h2 {
    color: red;
}

#Chaining Selector

h3.section-heading {
    color: blue;
}

#Attribute Selector

div[attribute="SomeValue"] {
    background-color: red;
}

#First Child Selector

p:first-child {
    font-weight: bold;
}

#No Children Selector

.box:empty {
  background: lime;
  height: 80px;
  width: 80px;
}
Comments