CSS: CSS Selectors

🗓 Last updated: 2026-11-30👤 Written by: Blake✓ Reviewed by: MOTO🏷 Category: CSS Tutorial

Selectors are the core of CSS — their job is to "select" the HTML elements you want to style. CSS offers multiple types of selectors, from simple tag selectors to complex selector combinations, giving you precise control over any element.

1. Basic Selectors

(1) Tag Selector (Element Selector)

Uses HTML tag names directly as selectors, matching all tags with the same name in the document.

CSS
/* All <p> elements turn red */
p {
/* Text color */
  /* Text color */
  /* Text color */
  /* Text color */
  color: red;
}

/* All <h1> elements turn blue */
h1 {
/* Text color */
  /* Text color */
  /* Text color */
  /* Text color */
  color: blue;
}

/* All <div> elements get a border */
div {
/* Box model properties */
  /* Box model properties */
  /* Box model properties */
  /* Box model properties */
  border: 1px solid black;
}

(2) Class Selector

Matches elements by their class attribute. Class names are prefixed with a period ..

CSS
/* All elements with class="highlight" */
.highlight {
/* Background style */
  /* Background style */
  /* Background style */
  /* Background style */
  background-color: yellow;
}

/* Only <p> elements with class="center" */
p.center {
/* Font style */
  /* Font style */
  /* Font style */
  /* Font style */
  text-align: center;
}

HTML elements can have multiple classes, separated by spaces:

HTML
<!-- Paragraph -->
<!-- Paragraph -->
<!-- Paragraph -->
<!-- Paragraph -->
<p class="highlight center">This text is both highlighted and centered</p>

(3) ID Selector

Matches elements by their id attribute, prefixed with a hash #.

CSS
/* Select element with id="header" */
#header {
/* Background style */
  /* Background style */
  /* Background style */
  /* Background style */
  background-color: #333;
/* Text color */
  /* Text color */
  /* Text color */
  /* Text color */
  color: white;
}

Note: An ID can only appear once per page. ID selectors are typically used for unique elements.

(4) Universal Selector

Uses an asterisk * to match all elements in the document.

CSS
/* Reset margins and padding for all elements */
* {
/* Box model properties */
  /* Box model properties */
  /* Box model properties */
  /* Box model properties */
  margin: 0;
/* Box model properties */
  /* Box model properties */
  /* Box model properties */
  /* Box model properties */
  padding: 0;
}

The universal selector is convenient, but be careful about performance — if complex styles are applied, it can affect page rendering speed.

▶ Example

Targeting elements with attribute selectors:

▶ Try it Yourself

2. Selector Specificity

When multiple selectors apply to the same element, the browser uses specificity rules to determine which style takes effect:

Selector Type Specificity Value
Inline styles (style attribute) 1000
ID selectors 0100
Class/Attribute/Pseudo-class selectors 0010
Tag/Pseudo-element selectors 0001
Universal selector 0000

Priority from high to low:

Inline styles > ID selectors > Class selectors > Tag selectors

(1) Specificity Calculation Example

CSS
/* Specificity: 0001 */
p {
/* Text color */
  /* Text color */
  /* Text color */
  /* Text color */
  color: black;
}

/* Specificity: 0010 */
.text {
/* Text color */
  /* Text color */
  /* Text color */
  /* Text color */
  color: blue;
}

/* Specificity: 0100 */
#special {
/* Text color */
  /* Text color */
  /* Text color */
  /* Text color */
  color: green;
}

/* Specificity: 0011 (class + tag) */
p.text {
/* Text color */
  /* Text color */
  /* Text color */
  /* Text color */
  color: red;
}

For the same <p class="text" id="special"> element, the final text color will be green (ID selector has the highest specificity).

(2) !important

CSS provides a "nuclear weapon" — !important — that forces a style to have the highest priority:

CSS
p {
/* Text color */
  /* Text color */
  /* Text color */
  /* Text color */
  color: red !important;
}

Don't use !important unless absolutely necessary — it makes style debugging difficult. Prioritize solving problems by increasing selector specificity.

▶ Example

Specificity showdown — which rule wins:

▶ Try it Yourself

The text renders green — the ID selector in #main .text gives it the highest specificity.



3. Best Practices for Selectors

  1. Use class selectors frequently: Classes are reusable and the most flexible selector
  2. Use ID selectors sparingly: IDs are unique, hard to reuse, and their high specificity can cause override issues
  3. Avoid over-specification: div.container ul li a is too specific; .nav-link is enough
  4. Keep selectors concise: Longer selectors are harder to maintain and affect performance

▶ Example

A complete example combining element, class, and ID selectors:

▶ Try it Yourself

The browser applies each rule to the matching element: h1 is navy, the highlighted paragraph has a yellow background, and the unique element is bold.


❓ FAQ

Q What is a CSS selector?
A A selector is the rule that decides which elements a style applies to, written before the declaration block. p targets every paragraph, .card targets every element with class="card", #header targets the one element with id="header". The browser finds the matching elements first, then applies the properties inside { } one by one.
Q Why is my CSS selector not working?
A Most likely causes, in order: missing the prefix — classes need .card and ids need #header, a bare card looks for a <card> tag; the name in the HTML is misspelled; your rule loses the specificity battle and gets overridden; the stylesheet never loaded; or a typo in a pseudo-class (:hover written as :hove). Open DevTools, search for your selector, and check whether the rule even shows up in the Styles panel.
Q When should I use class vs ID selectors?
A IDs can only appear once per page, suitable for unique elements (like top navigation, footer); classes can be reused, suitable for applying the same styles to multiple elements. In CSS, prefer classes; use IDs only for truly unique elements.
Q How do I use a class selector?
A Write class="card" in HTML and .card { padding: 20px; } in CSS — note the dot before the name. One element can carry several classes: class="card featured" (space-separated). A class can be reused as many times as you want — that's the biggest difference from id, and why classes are the default choice in real projects.
Q How do I target an id in CSS?
A Write id="top-bar" in HTML and #top-bar { height: 60px; } in CSS — hash sign in front. An id must be unique on the page, so it can't be reused. Its specificity is also high (100): if some style refuses to be overridden, check whether the winner's selector contains an id.
Q How is CSS specificity (weight) calculated?
A Remember four numbers: inline style 1000 > id 100 > class/pseudo-class 10 > tag 1, then add up the parts of a selector. #nav .item (110) beats .nav .item (20). Equal weight goes to whichever rule is written later. !important doesn't take part in the math — it jumps straight to the top.
Q How do I increase a selector's specificity?
A From lightest to heaviest: add a parent level (.card .title outweighs a bare .title), repeat the same class (.title.title doubles it), or switch to an id. !important is the last resort — it makes future maintenance harder, and in one project you should be able to count its uses on one hand.
Q What's the difference between descendant selectors (space) and child selectors (>)?
A Descendant selectors select all levels of child elements; child selectors only select direct children. For example, div p selects all p elements inside div at any level, while div > p only selects direct child p elements, regardless of grandchildren.
Q Does the universal selector * affect performance?
A Minimal use has little impact, but don't use it extensively. Since * matches all elements, the browser checks each one. If nested in complex selectors (like #nav * li), it may cause performance waste. Simple global resets like * { box-sizing: border-box; } are fine.

📖 Summary

📝 Exercises

  1. Create an HTML page with headings, paragraphs, and lists.
  2. Use tag selectors to set text color for all paragraphs.
  3. Use class selectors to set different background colors for specific elements (define at least 2 different classes).
  4. Use ID selectors to set special styles for one element on the page.
  5. Test: Apply tag, class, and ID selectors to the same element and observe which has the highest priority.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏