Types of CSS Selectors
- Element Selector: Targets all elements of a specific type (e.g.,
p,h1). - Class Selector: Targets elements with a specific class (e.g.,
.my-class). - ID Selector: Targets an element with a specific ID (e.g.,
#my-id). - Attribute Selector: Targets elements with a specific attribute (e.g.,
input[type="text"]). - Descendant Selector: Targets elements inside other elements (e.g.,
div p). - Group Selector: Targets multiple selectors at once (e.g.,
h1, h2, h3).
Example: CSS Selectors
/* Example */
p {
color: blue;
}
.highlight {
background-color: yellow;
}
#main-title {
font-size: 2em;
}
input[type="text"] {
border: 1px solid #ccc;
}
div p {
margin-bottom: 10px;
}
h1, h2, h3 {
font-family: Arial, sans-serif;
}
This example demonstrates different ways to select and style HTML elements.
Practice
Try experimenting with selectors:
- Combine class and element selectors for more specific targeting.
- Use attribute selectors to style form elements.
- Group selectors to apply the same style to multiple elements.
Continue Learning
Quick Check
Which symbol prefixes an ID selector?
Quick Check
Which brackets are used for attribute selectors?