TABLE OF CONTENTS
CSS selectors are used to find (or select) the HTML elements you want to style.
This guide covers the most commonly used selectors so you can target elements precisely and confidently.
Simple Selectors
Simple selectors target elements based on:
Element name
ID
Class
The universal selector (
*) which selects everything
Common Simple Selectors
| Selector | Example | What it Does |
|---|---|---|
element | p | Selects all <p> elements |
#id | #firstname | Selects the element with id="firstname" |
* | * | Selects all elements |
.class | .intro | Selects all elements with class="intro" |
element.class | p.intro | Selects <p> elements with class "intro" |
Usage Examples
/* Select all paragraph elements */
p {
color: blue;
}
/* Select element with specific ID */
#firstname {
font-weight: bold;
}
/* Select everything (universal selector) */
* {
margin: 0;
padding: 0;
}
/* Select all elements with a class */
.intro {
font-size: 18px;
}
/* Select only <p> elements with class intro */
p.intro {
background-color: yellow;
}Attribute Selectors
Attribute selectors target elements based on the presence or value of an attribute.
Common Attribute Selectors
| Selector | Example | Description |
|---|---|---|
[attribute] | [lang] | Elements that have a lang attribute |
[attribute=value] | [lang="it"] | Exact match of attribute value |
[attribute~=value] | [title~="flower"] | Attribute contains the word "flower" |
[attribute|=value] | [lang|="en"] | Value is "en" or starts with "en-" |
[attribute^=value] | [href^="https"] | Attribute begins with "https" |
[attribute$=value] | [href$=".pdf"] | Attribute ends with ".pdf" |
[attribute*=value] | [href*="w3schools"] | Attribute contains "w3schools" |
Usage Examples
Examples in Practice
Example 1: Styling External Links
Example 2: Form Styling
Example 3: Combining Selectors
Quick Reference Cheat Sheet
| Goal | Selector |
|---|---|
| Select all elements of a type | element (div, p, a) |
| Select by ID | #idname |
| Select by class | .classname |
| Select everything | * |
| Has attribute | [attr] |
| Attribute equals | [attr="value"] |
| Attribute starts with | [attr^="value"] |
| Attribute ends with | [attr$="value"] |
| Attribute contains | [attr*="value"] |
Tips
Specificity matters
#idis stronger than.class.classis stronger thanelement
Combine selectors for precision
Targets only:
<div>with class
"container"and attribute
data-active="true"
Case sensitivity
Attribute selectors are case-sensitive by default.
Use i for case-insensitive:
Great for dynamic styling
Attribute selectors are perfect for data-* attributes without needing JavaScript.