CSS Selectors
Basic Selectors
Selectors decide which HTML elements a CSS rule applies to. Here are the fundamental ones:
/* Universal selector — every element */
* {
margin: 0;
padding: 0;
}
/* Element (type) selector — every <p> */
p {
color: #333;
}
/* Class selector — every element with class="box" */
.box {
padding: 10px;
}
/* ID selector — the single element with id="header" */
#header {
background: black;
}
/* Grouping — apply the same rule to several selectors */
h1, h2, h3 {
font-family: sans-serif;
}
Class vs ID: a class can be reused on many elements; an ID must be unique on the page and used only once. Prefer classes for styling — save IDs for anchor links and JavaScript hooks.
Combinators
Combinators let you select elements based on their relationship to other elements.
/* Descendant — any <p> inside a <div>, at any depth */
div p {
color: green;
}
/* Child — only <p> elements that are direct children of <div> */
div > p {
color: orange;
}
/* Adjacent sibling — the <p> immediately after an <h1> */
h1 + p {
margin-top: 0;
}
/* General sibling — every <p> that follows an <h1> (not just the first) */
h1 ~ p {
color: gray;
}
Attribute Selectors
You can select elements based on the presence or value of an HTML attribute:
/* Has the attribute, any value */
input[required] {
border-color: red;
}
/* Exact value match */
input[type="text"] {
border: 1px solid #ccc;
}
/* Value contains a word (space-separated) */
a[class~="button"] {
padding: 8px 16px;
}
/* Value starts with */
a[href^="https"] {
color: green;
}
/* Value ends with */
a[href$=".pdf"] {
color: red;
}
/* Value contains a substring anywhere */
a[href*="example"] {
text-decoration: underline;
}
Pseudo-classes
A pseudo-class targets an element in a particular state — hovered, focused, first child, etc.
a:hover {
color: red;
}
a:visited {
color: purple;
}
input:focus {
outline: 2px solid blue;
}
input:disabled {
opacity: 0.5;
}
li:first-child {
font-weight: bold;
}
li:last-child {
color: gray;
}
li:nth-child(2n) {
background: #f0f0f0; /* every even list item */
}
li:nth-child(odd) {
background: #fafafa;
}
p:not(.intro) {
color: black; /* every p except ones with class "intro" */
}
Pseudo-elements
A pseudo-element targets a specific part of an element, rather than the whole thing:
p::first-letter {
font-size: 200%;
font-weight: bold;
}
p::first-line {
font-style: italic;
}
p::before {
content: "→ ";
}
p::after {
content: " ✓";
}
::selection {
background: yellow;
}
Note the double colon :: for pseudo-elements versus the single colon : for
pseudo-classes — this is the modern convention that keeps the two concepts visually distinct.