CSS Selectors
CSS
- Tag (Element) selectors
- Class selectors
- ID selectors
- Attribute selectors
- Pseudo selectors
1. Tag (Element) Selectors
These selectors target HTML elements directly by their tag name. Syntax:
Example: Target all paragraphs (<p>
):
2. Class Selectors
These selectors target HTML elements with a specific class attribute.
- Multiple elements can share the same class. Syntax:
HTML:
CSS:
3. ID Selectors
ID selectors target elements based on their unique ID attribute. IDs must be unique within a page. Syntax:
HTML:
CSS:
4. Attribute Selectors
Attribute selectors target HTML elements that have specific attributes or attribute-values. Syntax:
HTML:
CSS Examples:
- Select inputs with a type attribute:
- Select inputs with a specific attribute-value:
- Select elements with attribute starting with "Your":
5. Pseudo Selectors
Pseudo selectors target elements based on their state, position, or other special characteristics.
a. Pseudo-classes: Represent special states. Syntax:
Example: Style link on hover
Common Pseudo-classes:
Pseudo-class | Meaning | Example |
---|---|---|
``:hover` | Mouse hover | button:hover |
:active | During click | button:active |
:focus | Focused state (like form input) | input:focus |
:visited | Visited links | a:visited |
:first-child | First child of parent | li:first-child |
Example (focus):
b. Pseudo-elements: Represent specific parts of elements. Syntax: (uses double colon)
Example: Style first letter of paragraph:
Common Pseudo-elements:
Pseudo-element | Meaning | Example |
---|---|---|
::before | Insert content before element | div::before |
::after | Insert content after element | span::after |
::first-line | Targets first line of text | p::first-line |
::first-letter | Targets first letter of text | h1::first-letter |
Example (before/after):
HTML:
Summary & Quick Reference
Type | Usage | Example |
---|---|---|
Element Selector | Direct tag name | div {} |
Class Selector | Multiple-use class | .title {} |
ID Selector | Single unique identifier | #header {} |
Attribute Selector | Select by attributes | input[type="text"] {} |
Pseudo-class | Elements’ state | button:hover {} |
Pseudo-element | Parts of element | p::first-letter {} |