Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Put a period immediately before the class name: .notice. That selector matches every element whose class attribute contains the notice token, including elements that also have other classes.

<p class="notice">A notice</p>
<div class="notice urgent">An urgent notice</div>

.notice {
  color: navy;
}

The rest of the selector—an element name, another class, a space, a comma or an attribute condition—controls how narrowly it matches.

The basic class selector

A CSS class selector is a full stop (.) followed by a class name. For example, .notice selects any element whose whitespace-separated class list contains notice.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<div class="notice">System maintenance at midnight.</div>
<aside class="notice urgent">Service is currently degraded.</aside>

.notice {
  padding: 1rem;
  background: #eef;
}

Both elements receive the rule. The selector tests whether the class is present; it does not assume that the class is unique or that it is the only class. In the HTML, write class="notice". In CSS, write .notice, not class="notice".

#1 Best Overall
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

A class attribute is a list of tokens separated by whitespace. Therefore class="notice urgent" contains two classes, notice and urgent.

Narrow a class match with an element type

Place an element name directly before the period when only that element type should match. There is no space.

p.notice {
  font-weight: 700;
}

p.notice matches paragraphs with the notice class, but not a div or span carrying the same class. This is useful when a class is reused for different semantic elements and the style belongs to only one of them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Element plus several classes

You can continue chaining classes after the element name:

button.notice.urgent {
  border: 2px solid crimson;
}

This requires one button element to have both notice and urgent.

Select one element that has multiple classes

Write class selectors next to each other, with no whitespace, to require all of them on the same element.

.notice.urgent {
  border-left: 4px solid crimson;
}

This matches <div class="notice urgent"> and also <div class="urgent notice">; class order in the HTML does not matter. It does not match an element that has only one of the two classes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

.a.b versus .a .b

Selector What must match Example that matches
.a.b One element has both classes. <div class="a b">
.a .b An element with class b is a descendant of an element with class a. <div class="a"><span class="b"></span></div>

The space is a descendant combinator. It changes the relationship being tested; it is not decorative whitespace.

Select a direct child instead of any descendant

Use > when the second class must be an immediate child:

.menu > .item {
  display: flex;
}

This does not match .item nested one or more levels deeper inside another wrapper.

Select either of several classes

Separate alternatives with a comma. Each selector in the list is evaluated independently.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.notice, .urgent {
  font-weight: 700;
}

This styles an element with notice, an element with urgent, or an element with both. By contrast, .notice.urgent requires both classes on one element.

Keep each alternative readable on its own line when the list grows:

.notice,
.alert,
.banner {
  border-radius: .35rem;
}

Useful combinations with class selectors

Descendants, siblings and states

/* Any link inside a card */
.card a {
  color: #0645ad;
}

/* An item immediately after a selected item */
.item.selected + .item {
  margin-top: 1rem;
}

/* All later siblings of a selected item */
.item.selected ~ .item {
  opacity: .6;
}

/* A class while the pointer is over the element */
.button.primary:hover {
  filter: brightness(.9);
}

These selectors combine class matching with relationship or pseudo-class conditions. The class portion still follows the same period syntax.

Rank #3
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

Attributes and partial class-name tests

When a component library generates class names such as card-abc123, an attribute selector can match a prefix, but it is not equivalent to a real class-token match:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
[class^="card-"] {
  /* class attribute starts with card- */
}

[class*="card-"] {
  /* class attribute contains card- somewhere */
}

Use these only when the naming contract is intentional. A normal class selector, such as .card, is safer because it matches a complete token rather than an arbitrary substring.

Class names that need escaping

The identifier after . must be valid CSS identifier syntax. Names beginning with a digit, containing certain punctuation, or containing characters with special meaning may require a CSS escape.

<div class="123item">Legacy item</div>

/* Escaped leading digit */
.31 23item {
  color: darkorange;
}

The space after 31 terminates the hexadecimal escape; it is part of the escape syntax, not a descendant combinator. In new markup, prefer class names such as item-123 rather than forcing escapes.

Characters such as a period, colon or slash in a class value also need escaping when used in a selector. In JavaScript, CSS.escape() is the safest way to build a selector from untrusted or dynamically generated class text:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const className = "size:large";
const element = document.querySelector("." + CSS.escape(className));

Case sensitivity and matching details

In ordinary standards mode, class matching is case-sensitive: .Notice does not match class="notice". Keep capitalization consistent in HTML, CSS and JavaScript. Quirks mode can apply ASCII case-insensitive behavior, so do not rely on it; use standards mode with a <!doctype html> declaration.

Whitespace around class names is normalized as token separation. A selector for .notice matches class="notice urgent" and class=" urgent ", but not a token such as notices.

Specificity: why a matching rule may not win

Finding an element and winning the cascade are separate questions. A class selector contributes class-level specificity. If another declaration has greater specificity, an inline style, or !important, your matching rule can be overridden.

.notice {
  color: navy;
}

main .notice {
  color: black;
}

/* This later rule still loses to main .notice */
.notice {
  color: green;
}

Prefer predictable fixes over piling on selectors:

  • Inspect the element in browser developer tools and look at the Styles and Computed panels.
  • Remove an unintended competing rule or place the component rule in the correct cascade layer.
  • Match the necessary context without adding unrelated ancestors.
  • Reserve !important for deliberate utility or override systems.

Source order resolves ties between selectors with equal specificity, so a later rule wins only when the competing declarations have equal origin and specificity.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Using class selectors from JavaScript

CSS selector syntax is also accepted by DOM methods. Use querySelector for the first match and querySelectorAll for all matches.

const firstNotice = document.querySelector(".notice");
const notices = document.querySelectorAll(".notice");

notices.forEach((notice) => {
  notice.classList.add("visible");
});

If you only need a class-token lookup, getElementsByClassName("notice") avoids selector parsing and returns a live collection. querySelectorAll(".notice") returns a static NodeList; elements added later are not automatically included. For dynamic interfaces, run the query after rendering or use event delegation and a deliberate update strategy.

Testing a single element

const card = document.querySelector(".card");
if (card?.matches(".card.featured")) {
  console.log("This card has both classes");
}

matches() tests the element itself; it does not search descendants.

A practical debugging checklist

  • Nothing matches: confirm the selector starts with ., the class spelling is exact, and the element is present when the query or style is evaluated.
  • You wrote HTML syntax in CSS: replace class="notice" with .notice.
  • You used a space accidentally: change .notice .urgent to .notice.urgent when both classes belong to one element.
  • Only some elements match: check whether they actually share the complete class token; .notice will not match notices.
  • The rule appears crossed out: inspect specificity, source order, cascade layers, inline styles and !important.
  • Capitalization differs: make the class spelling identical in standards mode.
  • The name contains punctuation: escape it or rename the class to a CSS-friendly identifier.
  • JavaScript throws a selector error: pass dynamic names through CSS.escape() and verify every bracket, quote and combinator.
  • New content is missed: remember that a prior querySelectorAll result is static; query again or observe the rendering process.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is to inspect or document a page rather than style it, ScreenshotNeo can capture the result through one HTTP request. It accepts a URL and returns PNG, JPEG, WebP or PDF; consent banners, newsletter popups and chat widgets are removed before capture. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools to Claude, Cursor and other MCP clients.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

See the ScreenshotNeo API documentation for all options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo includes full-page and element captures, dark mode, device presets, custom viewports, retina scale, PDF controls, custom CSS and JavaScript, selector waits, network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone and geolocation. It also supports caching with a chosen TTL, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API and an OpenAPI specification. Existing parameter names used by other screenshot APIs also work.

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots; every feature is available on every plan, and yearly billing gives two months free. Sign up for ScreenshotNeo to use the free allowance.

Choosing the right selector pattern

Need Pattern
Any element with one class .name
One element type with a class button.name
Two classes on the same element .name.active
A class inside another class .parent .child
A direct child with a class .parent > .child
Either of two classes .name, .active

Start with the least specific selector that expresses the relationship you need. Add an element type, a second class or a combinator only when it narrows a real ambiguity. That keeps styles easier to override and selectors easier to maintain.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can one element have the same class more than once?

Repeating a token in the HTML class attribute does not create a second match or increase specificity; treat class names as a set of tokens and include each class once.

Should I use a class selector or an ID selector for component styling?

Use classes for reusable component and state styles. IDs are unique hooks and carry higher specificity, which can make later component overrides harder.

Why does a selector work in CSS but fail in querySelector()?

querySelector() requires a valid CSS selector string. Check JavaScript string escaping, escape dynamic class values with CSS.escape(), and remember that it returns only the first match.

How can I verify which class tokens an element actually has?

Inspect the element in developer tools or run element.classList in the console; classList exposes the browser’s parsed token list rather than the raw attribute formatting.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.