Web Development · Module 3 · Lesson 11 min read

Selectors & Specificity

What CSS does

CSS (Cascading Style Sheets) controls how HTML looks: colours, fonts, spacing and layout.

CSS
selector { property: value; }
h1 { color: navy; font-size: 2rem; }

Add CSS with a <link rel="stylesheet" href="style.css"> in <head> (best), a <style> block, or the inline style="" attribute (avoid).

Selectors

SelectorMatches
pall <p> elements
.cardclass="card"
#headerid="header"
nav a<a> inside <nav> (descendant)
ul > lidirect children only
a:hover, input:focus, li:nth-child(2)states and positions (pseudo-classes)
p::first-line, .btn::beforeparts of elements (pseudo-elements)
input[type="email"]attributes

The cascade: who wins?

When rules conflict, the browser decides by:

  1. Importance: !important (avoid using it).
  2. Specificity: inline style > #id > .class / :hover / [attr] > element.
  3. Order: later rules win when specificity is equal.

Inheritance

Text properties (color, font-family, line-height) are inherited by children; box properties (margin, border) aren't.

💡 Style mostly with classes. They're reusable and keep specificity low and predictable.

Example

HTML
<style>
  p { color: gray; }            /* element: lowest */
  .note { color: green; }       /* class beats element */
  #special { color: crimson; }  /* id beats class */
  nav a:hover { text-decoration: underline; }
  li:nth-child(odd) { background: #f3f4f6; }
</style>

<p>Gray paragraph</p>
<p class="note">Green note</p>
<p class="note" id="special">Crimson (id wins)</p>

<ul>
  <li>One</li><li>Two</li><li>Three</li>
</ul>