Back to subject
CSS3/Selectors

Reading Three Kinds of Selectors Together

Practical lesson

Let's read a small page that uses an element selector, a class selector, and a combined selector, and see why each was chosen.

p { line-height: 1.6; } is an element selector it applies to EVERY paragraph on the page automatically, no class needed. This is perfect for a base default you want everywhere, like readable line spacing.

.highlight { color: #1E2A5A; font-weight: bold; } is a class selector. Unlike the element selector above, this does nothing until you actually add class="highlight" to a specific tag <p class="highlight">Styled by a class selector.</p>. Because it's a class, you could add class="highlight" to five different paragraphs, or even a <span> or <h3>, and every one of them would pick up this exact same navy, bold styling.

Now imagine a third rule: .card p { font-size: 14px; }. This combined selector only touches <p> tags that live inside something with class="card" a completely separate <p> elsewhere on the page, with no .card ancestor, stays untouched at its normal size. This is how real sites give the same tag (<p>) different looks depending on which section of the page it's in, without needing a unique class on every single paragraph.

Try it yourself
Code

Starter example

Code
<link rel="stylesheet" href="style.css">

<p>Base paragraph.</p>
<p class="highlight">Styled by a class selector.</p>
<div class="card">
  <p>A paragraph inside the card, smaller by default.</p>
</div>
Live preview