Skip to content
AgileLogics
5 min read

Basic Selectors

Prerequisites: CSS syntax and how it is applied

Selectors choose which elements a rule styles.

/* Type selector: every <p> */
p { line-height: 1.6; }

/* Class selector: every element with class="card" */
.card { border: 1px solid #ddd; }

/* Several classes on one element: class="card featured" */
.card.featured { border-color: gold; }

/* Type + class: only <a class="button">, not <button class="button"> */
a.button { text-decoration: none; }

/* ID selector: the element with id="site-header" */
#site-header { background: #222; }

/* Universal selector: every element */
* { margin: 0; }

/* Selector list: several selectors, one rule */
h1, h2, h3 { font-family: Georgia, serif; }

Classes are your main tool

  • An element can have many classes: class="card featured large".
  • Many elements can share a class.
  • Class names are case-sensitive: .Card doesn't match class="card".
  • Use ids sparingly in CSS. An id selector is so specific (next lessons) that it's hard to override, and an id must be unique on the page, so the rule can't be reused.

Try it

<style>
  p { color: gray; }
  .lead { color: black; font-size: 1.25rem; }
  .lead.warning { color: darkred; }
  #special { font-style: italic; }
</style>
<p>Normal</p>
<p class="lead">Lead</p>
<p class="lead warning">Lead warning</p>
<p class="warning">Just warning</p>
<p id="special" class="lead">Special lead</p>
<script>
  for (const p of document.querySelectorAll("p")) {
    const s = getComputedStyle(p);
    console.log(p.textContent.padEnd(13), s.color, s.fontSize, s.fontStyle);
  }
</script>
Normal        rgb(128, 128, 128) 16px normal
Lead          rgb(0, 0, 0) 20px normal
Lead warning  rgb(139, 0, 0) 20px normal
Just warning  rgb(128, 128, 128) 16px normal
Special lead  rgb(0, 0, 0) 20px italic
  • "Just warning" is gray: .lead.warning needs both classes.
  • "Special lead" is black, 20 pixels (from .lead), and italic (from #special) — rules combine; they don't replace each other wholesale.

Practice

Write one rule that makes all h2s and every element with the class subtitle dark green, and a rule for button elements with the class primary only.

Show solution
h2, .subtitle {
  color: darkgreen;
}

button.primary {
  background: darkgreen;
  color: white;
}