Type, Class & ID Selectors
Type selectors target elements by HTML tag. Class selectors target elements with a specific class. ID selectors target a single element by ID. Each has different specificity and use cases.
Type Selectors
CSS
/* Type selector: targets all elements of that type */
div {
margin: 0;
}
p {
line-height: 1.6;
}
a {
color: blue;
}
/* Multiple type selectors (comma-separated) */
h1, h2, h3 {
font-weight: bold;
}Class Selectors
CSS
/* Class selector: targets elements with that class */
.primary-button {
background-color: blue;
color: white;
}
.alert {
background-color: red;
padding: 10px;
}
/* Multiple classes on same element */
.text-large {
font-size: 24px;
}
.bold {
font-weight: bold;
}ID Selectors
CSS
/* ID selector: targets element with that ID (unique) */
#header {
background-color: navy;
color: white;
height: 80px;
}
#footer {
background-color: gray;
margin-top: 40px;
}
/* ID should be unique per page */
#main-content {
max-width: 1200px;
margin: 0 auto;
}Specificity
Selector | Type | Specificity |
|---|---|---|
div | Type | Low (0,0,1) |
.button | Class | Medium (0,1,0) |
#header | ID | High (1,0,0) |
Warning
Avoid over-using ID selectors. They have high specificity and make CSS harder to maintain. Prefer classes for styling.
Note
Type selectors target elements, classes target groups, IDs target unique elements. Classes are most flexible; ID selectors have high specificity and should be used sparingly.
Next
The cascade: [The Cascade](/css/the-cascade).