1. Basic Selectors
A. Element Selector
Targets all instances of an HTML element:
p { color: blue; /* Styles ALL <p> tags and changes their color to blue */ }
B. Class Selector (.)
Targets elements with a specific class:
e.g <div class=“highlight”>
.highlight { background: yellow; /* Styles <div class="highlight"> */ }
-
Multiple elements can share the same class
-
One element can have multiple classes as follows:
-
<p class=“highlight urgent“>…</p>
C. ID Selector (#)
Targets a single unique element:
#header { font-size: 24px; /* Styles <div id="header"> and changes it's font size. */ }
-
IDs must be unique in a page
-
More specific than classes (overrides them)
2. Selector Comparison
Selector | Example | When to use |
---|---|---|
Element | h1 |
Styling all elements of one type |
Class | .menu |
Reusable styles for multiple elements |
id | #login-form |
Unique element styling (use sparingly) |
3. Advanced Selector Techniques
A. Grouping Selectors
Apply same styles to multiple selectors:
h1, h2, h3 { font-family: Arial; /* Styles ALL headings by changing their font family */ }
B. Combining Selectors
-
Element + Class
-
p.special { /* Only <p class="special"> */ color: purple; }
-
Nested Element
-
nav a { /* Links INSIDE <nav> */ text-decoration: none; }
C. Universal Selector (*)
Selects every element as shown in the sample code below.
* { margin: 0; /* Resets margins globally */ box-sizing: border-box; }
4. Specificity Hierarchy
When multiple selectors target the same element:
-
ID for example
#header
) → Most powerful -
Class for example
.button
-
Element (
p
) → Least powerful
Example Conflict:
#title { color: red; } /* Wins! */ .title { color: blue; } h1 { color: green; }
<h1 id=“title“ class=“title“>Hello</h1> will appear red