Skip to main content

Command Palette

Search for a command to run...

CSS Selectors 101: Targeting Elements with Precision

Published
3 min read

CSS selectors tell the browser which elements to style. Without them, you'd style everything the same way.

The "Who" in Styling

Think of selectors like addressing people:

  • "Hey you" → Element selector (vague)

  • "Person with blue shirt" → Class selector (specific)

  • "John Smith" → ID selector (unique)

1. Element Selector (Tag Name)

Styles all elements of that type:

p {
  color: blue;
}
/* All <p> tags become blue */

2. Class Selector (Most Used)

Styles elements with that class:

<p class="important">Text</p>
.important {
  font-weight: bold;
  color: red;
}

Multiple elements can share the same class. Use for reusable styles.

3. ID Selector (Unique)

Styles one specific element:

html

<div id="header">Site Header</div>
#header {
  background: black;
  color: white;
}

Only one element per page should have each ID. Use for unique elements.

4. Group Selectors

Apply same styles to multiple selectors:

h1, h2, h3 {
  font-family: Arial;
}
/* Styles all h1, h2, AND h3 elements */

5. Descendant Selectors

Style elements inside other elements:

<div class="article">
  <p>This text is styled.</p>
</div>
<p>This text is NOT styled.</p>
.article p {
  color: gray;
}
/* Only <p> tags INSIDE .article */

Selector Priority (Specificity)

When multiple selectors target the same element:

ID > Class > Element

Example:

p { color: blue; }           /* Element - weakest */
.special { color: green; }   /* Class - stronger */
#unique { color: red; }      /* ID - strongest */
<p id="unique" class="special">What color?</p>
<!-- Result: RED (ID wins) -->

Practical Example

<h1>Title</h1>
<p class="intro">Introduction</p>
<p>Regular text</p>
<div id="footer">Copyright</div>
/* Element selector */
p { margin: 10px; }

/* Class selector */
.intro { font-size: 1.2em; }

/* ID selector */
#footer { background: #eee; }

/* Group selector */
h1, .intro { color: navy; }

/* Descendant selector */
div p { font-style: italic; }

Quick Reference

SelectorTargetsExampleUse When
pAll <p> elementsp { }Default styling
.classElements with class="class".alert { }Reusable styles
#idElement with id="id"#main { }Unique element
a, bBoth a and bh1, h2 { }Shared styles
.parent p<p> inside .parent.menu li { }Nested elements

Pro tip: Start with element/class selectors. Use IDs sparingly. Right-click any webpage → "Inspect" to see real selectors in action.

Enjoyed reading this blog? Let's connect!
🐦 Twitter/X: @rohan_gupta96
💼 LinkedIn: https://www.linkedin.com/in/rohangupta9896
🐙 GitHub: https://github.com/rohan9896