<p class="highlight">This paragraph is highlighted.</p>
<p class="error">This is an error message.</p>
<p class="highlight error">This has two classes.</p>
3. ID Selectors
Target a specific element with a unique ID. Use a hash (#) prefix. IDs should be unique! Note: Use classes instead of IDs in most cases.
<header id="header">Top of page</header>
<footer id="footer">Bottom of page</footer>
4. Descendant Selectors
Target elements nested inside other elements. Use a space to separate:
/* Target all p tags inside a div */
div p {
color: blue;
}
/* Target all links inside navigation */
nav a {
color: white;
}
/* Target all list items inside an unordered list */
ul li {
margin: 5px 0;
}
5. Attribute Selectors
Target elements based on their attributes:
/* Target all inputs with type="text" */
input[type="text"] {
border: 1px solid blue;
}
/* Target all links with href starting with "https" */
a[href^="https"] {
padding-right: 20px;
}
/* Target all images with alt attribute */
img[alt] {
border: 1px solid gray;
}
/* Target all elements with disabled attribute */
[disabled] {
opacity: 0.5;
}
6. Pseudo-Classes
Target elements based on their state or position. Use a colon (:):
/* Links that haven't been visited */
a:link {
color: blue;
}
/* Links that have been visited */
a:visited {
color: purple;
}
/* When hovering over an element */
button:hover {
background: darkblue;
}
/* When an element has focus */
input:focus {
outline: 2px solid blue;
}
/* First child element */
li:first-child {
font-weight: bold;
}
/* Last child element */
li:last-child {
border-bottom: none;
}
/* Every other element */
li:nth-child(even) {
background: #f0f0f0;
}
Try hovering over this text to see pseudo-classes in action:
Hover Me
7. Pseudo-Elements
Target specific parts of elements. Use double colons (::):
/* First letter of text */
p::first-letter {
font-size: 200%;
font-weight: bold;
}
/* First line of text */
p::first-line {
color: blue;
}
/* Content before an element */
p::before {
content: "→ ";
color: red;
}
/* Content after an element */
p::after {
content: " ←";
color: red;
}
8. Combinators
Combine multiple selectors in specific ways:
Combinator
Name
Example
Meaning
Descendant
div p
All p inside any div
>
Child
div > p
All p that are direct children of div
+
Adjacent Sibling
h2 + p
p immediately after h2
~
General Sibling
h2 ~ p
All p that come after h2 (same parent)
,
Multiple
h1, h2, h3
h1 AND h2 AND h3
Specificity
When multiple selectors target the same element, more specific selectors win. Specificity order (from lowest to highest):