← Back to Tutorials Chapter 5

Selectors & Effects

Combinators

Combinators define relationships between selectors.

Descendant Selector (space)

Selects all matching descendants regardless of depth.

article p {
  color: gray;
}

Child Selector (>)

Selects only direct children.

ul > li {
  list-style: none;
}

Adjacent Sibling Selector (+)

Selects an element immediately preceded by a specific sibling.

h2 + p {
  font-weight: bold;
}

General Sibling Selector (~)

Selects all siblings that follow a specific element.

h2 ~ p {
  color: #666;
}

Pseudo-classes

Pseudo-classes describe a special state of an element.

:hover

a:hover {
  color: orange;
}

:focus

input:focus {
  border-color: blue;
}

:nth-child

li:nth-child(odd) {
  background: #f0f0f0;
}

li:nth-child(3n) {
  border-bottom: 1px solid #ccc;
}

:first-child and :last-child

p:first-child {
  margin-top: 0;
}

p:last-child {
  margin-bottom: 0;
}

Pseudo-elements

Pseudo-elements target a specific part of an element.

::before and ::after

.note::before {
  content: "\26A0";
  margin-right: 5px;
}

.link::after {
  content: " \2197";
}

::first-line

p::first-line {
  font-variant: small-caps;
}

Attribute Selectors

/* Exact match */
input[type="text"] { border: 1px solid gray; }

/* Contains */
a[href*="example"] { color: green; }

/* Starts with */
a[href^="https"] { font-weight: bold; }

/* Ends with */
img[src$=".png"] { border-radius: 4px; }

Opacity

.faded {
  opacity: 0.5;
}
Diagram showing selector specificity cascade

Practice Task

Style a table with alternating row colors using :nth-child(even), add an icon before each link using ::before, and apply a hover effect that changes background color.