Chapter 6 of 15

CSS Selectors Made Simple: Class, ID and More

Selectors decide which elements get a style. A handful of them covers most of what you need.

Element, class and id

The same four paragraphs three times, with different ones highlighted by p, .warning and #intro
Blue = selected. p picks all paragraphs, .warning picks class="warning", #intro picks id="intro".
HTML
<p>Normal paragraph</p>
<p class="warning">Careful!</p>
<p id="intro">Welcome text</p>
CSS
p        { color: black; }   /* every <p> */
.warning { color: red; }     /* class: starts with a dot */
#intro   { font-size: 22px; }/* id: starts with # */
  • A class can be used on many elements. Use classes for most styling.
  • An id must be unique: only one per page. Use it for links like #contact, not much for styling.
  • One element can have many classes: class="btn btn-big".

Group and nest selectors

Links inside nav are selected; links inside footer are not
A space between selectors means "inside". nav a = links inside nav only.
CSS
h1, h2, h3 { font-family: Georgia, serif; }  /* group: same style for all */

nav a { text-decoration: none; }  /* descendant: <a> inside <nav> */

ul > li { margin: 4px; }          /* child: only direct children */

a.btn { padding: 10px; }          /* <a> that also has class btn */

Pseudo-classes: hover, focus and more

A pseudo-class picks an element when it is in a special state. It uses a colon :.

CSS
a:hover        { color: green; }      /* mouse is on it */
a:focus        { outline: 2px solid; }/* selected by keyboard */
li:first-child { font-weight: bold; } /* first item */
li:nth-child(even) { background: #eee; } /* 2nd, 4th, 6th... */
Result in the browser
  • First item (bold)
  • Second item
  • Third item
  • Fourth item

Attribute selectors

You can pick elements by their attributes, using square brackets:

CSS
input[type="email"] { border-color: #2563eb; }   /* only email boxes */
a[href^="https"]     { font-weight: bold; }      /* links that start with https */
a[href$=".pdf"]      { color: #dc2626; }         /* links that end with .pdf */
img[alt=""]          { outline: 3px solid red; } /* find images with empty alt */

^= means "starts with" and $= means "ends with". The last line is a handy trick: it shows a red outline on every image that is missing a description.

Pseudo-elements: ::before and ::after

A pseudo-element styles a part of an element, or adds small decorations without new HTML. It uses two colons.

CSS
.price::before { content: "₹"; }         /* add a symbol before */
.new::after    { content: " NEW"; color: #dc2626; font-weight: bold; }
p::first-letter { font-size: 2em; }      /* big first letter */
input::placeholder { color: #9ca3af; }   /* style the hint text */
Result in the browser

₹499

Summer sale NEW

Do not hide content hereText added with content is decoration. Screen readers may skip it, and Google may ignore it. Put real information in the HTML.

How to name your classes

Good class names make CSS easy to read months later. Simple rules:

  • Name by what it is, not how it looks: .warning, not .red-text. If you later make warnings orange, the name still fits.
  • Use small letters and dashes: .product-card.
  • Name parts after their parent: .card, .card-title, .card-button. Now you know where each class belongs.
HTML
<div class="card">
  <h3 class="card-title">Mango juice</h3>
  <a class="card-button" href="#">Order</a>
</div>

Specificity: which selector is stronger?

When two rules fight, the more specific selector wins, even if it comes first. Think of it as points:

Bar chart: element weakest, then class, id, and inline style strongest
Specificity is a strength score. Use classes most of the time to keep things simple.
Selector typeStrength
Inline style style="..."Strongest
id #introVery strong
class .warning, :hoverMedium
element pWeak
CSS
.warning { color: red; }
p        { color: blue; }  /* comes later, but weaker. Text stays red */
Keep it simpleUse mostly classes. Avoid ids and !important for styling. Then you will rarely have fights between rules.

Why to avoid !important

CSS
p { color: blue !important; }

!important makes a rule beat almost everything. It feels like a quick fix, but then the next fix also needs !important, and soon nothing can be changed easily. If a rule is not working, open DevTools, find which rule wins (it is not crossed out), and make your selector a little more specific instead.

Mini project: a menu with hover and active states

HTML
<nav class="menu">
  <a href="index.html" class="active">Home</a>
  <a href="about.html">About</a>
  <a href="contact.html">Contact</a>
</nav>
CSS
.menu a {
  display: inline-block;
  padding: 10px 16px;
  border-radius: 8px;
  color: #1f2937;
  text-decoration: none;
}
.menu a:hover  { background: #f1f4f8; }
.menu a.active { background: #2563eb; color: white; }
.menu a:focus-visible { outline: 3px solid #2563eb; }
Result in the browser
Home About Contact

On each page, move the active class to the link of that page. Visitors always see where they are. The :focus-visible rule helps people who use the keyboard instead of a mouse.

Common mistakes

ProblemFix
.card .title does nothingCheck the HTML: is the title really inside the card? A space means "inside".
.btn.big vs .btn .bigNo space = same element has both classes. Space = .big inside .btn.
Class in HTML has a dotWrite class="card" in HTML and .card in CSS
Rule loses for no clear reasonLook in DevTools for a stronger selector that wins

Cheat sheet

SelectorPicks
pAll paragraphs
.cardElements with class="card"
#topThe element with id="top"
nav aLinks inside nav
ul > liDirect children only
h1, h2Both
a:hoverLink under the mouse
li:nth-child(2)Second item
[type="email"]By attribute
::beforeDecoration before content

Practice time

  1. Make a .btn class and use it on two links.
  2. Change the button colour on :hover.
  3. Give every second row of a list a light grey background.
  4. Add a red outline to any image with empty alt text using an attribute selector.
  5. Build the menu with an active state on every page of your site.

Quick summary

  • p = element, .name = class, #name = id.
  • Use a space for "inside", a comma for "and".
  • Use classes for most styling and avoid ids for it.