Reading history

CSS Selectors and Specificity Explained With Examples

4 min read Updated 0 views

Learn CSS selectors: element, class, id, attribute and group selectors, combinators, pseudo-classes, specificity and the cascade.

A CSS rule has two parts: a selector that picks which elements to style, and a block of declarations that says how. Selectors range from simple (all paragraphs) to precise (the first item of every list, or email inputs only). When several rules target the same element, specificity and the cascade decide which one wins. This lesson covers both.

In this lesson you will learn

  • Element, class, id, attribute and group selectors
  • Descendant and child combinators
  • Pseudo-classes such as :hover and :nth-child()
  • How specificity decides which rule wins
  • Where to put your CSS

The Main Selectors

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Selectors</title>
  <style>
    p            { color: #333; }          /* element selector */
    .note        { background: #fff3cd; }  /* class selector */
    #main-title  { color: #00695c; }       /* id selector */
    ul li        { color: #6a1b9a; }       /* descendant selector */
    a:hover      { color: crimson; }       /* pseudo-class */
    input[type="email"] { border: 2px solid teal; }  /* attribute selector */
    h2, h3       { font-family: sans-serif; }        /* group */
  </style>
</head>
<body>
  <h2 id="main-title">CSS Selectors</h2>
  <p>A normal paragraph.</p>
  <p class="note">A paragraph with class="note".</p>
  <ul><li>List item inside a ul</li></ul>
  <p><a href="#">Hover over this link</a></p>
  <input type="email" placeholder="email field">
</body>
</html>

Result

  • p selects every <p>. .note selects elements with class="note". #main-title selects the one element with that id.
  • ul li (with a space) selects li elements anywhere inside a ul. ul > li would select direct children only.
  • a:hover applies only while the mouse is over the link. Try it in the preview.
  • input[type="email"] selects by attribute value.
  • h2, h3 applies one rule to several selectors.

Specificity: Which Rule Wins?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Specificity</title>
  <style>
    p           { color: blue; }    /* specificity 0-0-1 */
    .msg        { color: green; }   /* 0-1-0 wins over p */
    #special    { color: red; }     /* 1-0-0 wins over .msg */
    .msg.urgent { color: orange; }  /* 0-2-0 */
    li:first-child { font-weight: bold; }
    li:nth-child(even) { background: #eee; }
  </style>
</head>
<body>
  <p>Only the element rule applies: blue.</p>
  <p class="msg">Class beats element: green.</p>
  <p class="msg" id="special">ID beats class: red.</p>
  <p class="msg urgent">Two classes beat one: orange.</p>
  <ol><li>First (bold)</li><li>Second (grey)</li><li>Third</li><li>Fourth (grey)</li></ol>
</body>
</html>

Result

Specificity is scored in three columns, IDs – classes – elements, and compared from left to right:

SelectorScore
p0-0-1
.msg, :hover, [type]0-1-0
.msg.urgent0-2-0
#special1-0-0
style="..." attributebeats all selectors
  • When two rules have the same specificity, the one written later wins. That is the “cascade” in Cascading Style Sheets.
  • :first-child and :nth-child(even) select by position, which makes zebra-striped lists and tables easy.
  • !important overrides normal specificity, but overusing it makes CSS very hard to maintain.

Where to Write CSS

MethodExampleUse
External file<link rel="stylesheet" href="style.css">Best for real sites; one file styles every page
Internal<style>...</style> in the headSingle pages and demos, like the ones here
Inlinestyle="color:red"Quick tests only

Common Mistakes

  1. Forgetting the dot or hash: note { } looks for a <note> element.
  2. Styling with ids everywhere. Their high specificity makes later changes hard; prefer classes.
  3. Missing semicolons between declarations, which can break the next line.
  4. Reaching for !important instead of fixing specificity.

Practice Exercises

Exercise 1. Make every link inside <nav> white with no underline.

Show answer
nav a {
  color: white;
  text-decoration: none;
}

Exercise 2. Give odd table rows a light grey background.

Show answer
tr:nth-child(odd) { background: #f5f5f5; }

Frequently Asked Questions

Should I use classes or ids for styling?

Use classes. They are reusable and have lower specificity. Keep ids for page anchors and JavaScript.

What is the universal selector?

* selects every element. It is often used in resets such as * { box-sizing: border-box; }.

Summary

  • A rule is a selector plus declarations: selector { property: value; }.
  • Element, class, id, attribute, combinator and pseudo-class selectors cover most needs.
  • Specificity (IDs, classes, elements) decides conflicts; on a tie, the later rule wins.
  • Prefer external stylesheets and class selectors.

Next: The CSS Box Model.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *