🟢 CSS Selectors
CSS selectors are patterns used to target and style specific HTML elements. They define which elements in your HTML the styles should apply to.There are many types of selectors, ranging from simple to advanced.
1. Element Selector
Selects HTML elements based on the element name.🔧 Example:
p {
color: blue;
}
<p>This paragraph will be blue.</p>
🖼️ Output Behavior:
All <p> elements will have blue text.2. ID Selector
Selects a single element by its unique id.🔧 Example:
#intro {
font-weight: bold;
}
<p id="intro">This is bold text using an ID selector.</p>
🖼️ Output Behavior:
Only the element with id="intro" will be bold.3. Class Selector
Selects one or more elements with a specific class.🔧 Example:
.highlight {
background-color: yellow;
}
p class="highlight">Highlighted paragraph.</p>
<div class="highlight">Highlighted div.</div>
🖼️ Output Behavior:
Both the paragraph and div will have a yellow background.
4. Grouping Selector
Applies the same style to multiple selectors.🔧 Example:
h1, h2, p {
margin-bottom: 20px;
}
🖼️ Output Behavior:
Adds bottom margin to all h1, h2, and p elements.
5. Universal Selector
Targets all elements on the page.🔧 Example:
* {
margin: 0;
padding: 0;
}
🖼️ Output Behavior:Resets margin and padding for all elements—commonly used in CSS resets.
6. Descendant Selector
Selects elements that are nested inside other elements.🔧 Example:
div p {
color: green;
}
<div>
<p>This paragraph will be green.</p>
</div>
🖼️ Output Behavior:Only paragraphs inside div elements will turn green.
7. Child Selector
Selects elements that are direct children of another element.🔧 Example:
ul > li {
list-style-type: square;
}
🖼️ Output Behavior:Changes bullet style of immediate li children inside ul.
8. Pseudo-classes
Select elements in a specific state (like hover or first-child).🔧 Example:
a:hover {
color: red;
}
🖼️ Output Behavior:Changes link color to red when hovered.
📘 Summary Table
Selector Type | Symbol | Targets |
---|---|---|
Element | p |
All <p> elements |
ID | #id |
One element with a specific ID |
Class | .class |
All elements with that class |
Grouping | a, b |
Multiple elements |
Universal | * |
Every element |
Descendant | A B |
B inside A |
Child | A > B |
Direct B inside A |
Pseudo-class | a:hover |
Element in a specific state |