๐ฏ CSS COURSE โ MODULE 2: SELECTORS
๐ File: selectors.md
๐จ CSS Selectors
๐ Introduction
CSS selectors are used to target HTML elements so you can style them.
๐ No selectors = no control over styling ๐ Strong selectors = professional CSS
๐งฑ 1. Element Selector
Targets all elements of a specific type.
p {
color: blue;
}
๐ก Example
<p>Hello World</p>
โ All <p> elements become blue
๐ฆ 2. Class Selector
Targets elements with a class.
.text {
color: red;
}
<p class="text">Hello</p>
โ Used for reusable styles
๐ฅ 3. ID Selector
Targets a single unique element.
#title {
color: green;
}
<h1 id="title">Welcome</h1>
โ Only ONE element per page
๐ง Important Rule
| Selector | Symbol | Usage |
|---|---|---|
| Element | none | p, h1 |
| Class | . | reusable |
| ID | # | unique |
๐งฉ 4. Group Selector
Apply same style to multiple elements.
h1,
p,
a {
color: purple;
}
โ Saves time
๐ 5. Universal Selector
Targets ALL elements.
* {
margin: 0;
padding: 0;
}
โ Used for reset styles
๐งฑ 6. Descendant Selector
Targets elements inside another element.
div p {
color: blue;
}
<div>
<p>Hello</p>
</div>
โ Only <p> inside <div>
๐ถ 7. Child Selector
Targets direct children only.
div > p {
color: red;
}
โ More strict than descendant selector
๐ 8. Adjacent Sibling Selector
Targets element right after another.
h1 + p {
color: green;
}
<h1>Title</h1>
<p>Paragraph</p>
โ Only first <p> after <h1>
๐ง Real Example
<div class="box">
<h1 id="title">Hello</h1>
<p class="text">Welcome to CSS</p>
</div>
.box {
background: lightgray;
}
#title {
color: blue;
}
.text {
color: red;
}
๐ Selector Priority (VERY IMPORTANT)
CSS follows priority:
ID > Class > Element
Example:
p {
color: blue;
}
.text {
color: red;
}
#id {
color: green;
}
โ ID always wins
โ ๏ธ Common Mistakes
- Using too many IDs โ
- Not understanding specificity โ
- Overusing
*selector โ - Mixing selectors randomly โ
๐งช Mini Exercise
Create a page with:
- A heading (ID styled)
- Three paragraphs (class styled)
- One container div
- Use:
- element selector
- class selector
- ID selector
- group selector