In this article
Simple Selectors Attribute Selectors Examples in Practice Example 1: Styling External Links Example 2: Form Styling Example 3: Combining Selectors Quick Reference Cheat SheetCSS 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<pelements |
| #id | #firstname | Selects the element withid="firstname" |
| Selectsallelements | ||
| .class | .intro | Selects all elements withclass="intro" |
| element.class | p.intro | Selects<pelements with class"intro" |
Usage Examples
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 alangattribute | ||
| [attribute=value] | [lang="it"] | Exact match of attribute value | ||
| [attribute=value] | [title="flower"] | Attribute contains theword"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
is stronger than
is stronger than
Combine selectors for precision
Targets only:
with class
and attribute
Case sensitivity
Attribute selectors are case-sensitive by default.
Use for case-insensitive:
Great for dynamic styling
Attribute selectors are perfect for attributes without needing JavaScript.