CSS Selectors
Used to select HTML elements based on element name, id, class, attribute, and more.
Primary Selectors
Element Selector
Selects elements based on the HTML tag name.
p { text-align: center; color: red; }
ID Selector
Selects a single element with a specific id.
#intro { color: white; background-color: grey; }
<div id="intro"><p>This paragraph is in the intro section.</p></div>
Class Selector
Can be used multiple times on a page.
.first { font-size: 200%; }
<p class="first">This is a paragraph.</p>
Element + Class Selector
p.center { text-align: center; color: red; }
Nested Selectors
Descendant Selector
#intro .first em { color: pink; background-color: gray; }
Adjacent Sibling Selector
p + p { font-style: italic; font-weight: bold; }
Direct Child Selector
div > span { background: DodgerBlue; }
Multiple Classes
.apple { color: red; }
.orange { color: orange; }
.small { font-size: 16px; }
.apple.orange { font-style: italic; }
Attribute Selector
a[title="menu"] { text-decoration: none; color: #962103; font-size: 22px; }
Grouping Selectors
h1, h2, p { text-align: center; color: red; }
Combining Selectors
h1#header.intro { text-decoration: underline; color: #C00; }
Pseudo Selectors
:hover
a:hover { color: #D48F29; text-decoration: underline overline; }
:visited
a:visited { color: #D48F29; }
:active
html:active { background: yellow; }
:first-line
p:first-line { color: blue; background-color: lightblue; }
::before and ::after
h1::before { content: "« "; } h1::after { content: " »"; }
Structural Pseudo-Classes
:nth-child(2n)
tr:nth-child(2n) { background: #95313b; color: #fff; }
:nth-child(2n+1)
tr:nth-child(2n+1) { background: #95313b; color: #fff; }
:nth-of-type(2)
p:nth-of-type(2) { background: #95313b; color: #fff; }