Middle+
What do you know about CSS selectors and specificity?
sobes.tech AI
Answer from AI
CSS selectors are patterns that allow you to select HTML elements to apply styles to them. They come in different types: by tag (e.g., div), by class (.class), by ID (#id), by attributes ([type="text"]), pseudo-classes (:hover), and pseudo-elements (::before).
Specificity is a mechanism that determines which style will be applied if multiple selectors with conflicting rules match the same element. Specificity is calculated based on a formula that considers the number of IDs, classes, tags, and inline styles:
- Inline styles (inline style) have the highest specificity.
- The number of IDs in the selector.
- The number of classes, attributes, and pseudo-classes.
- The number of tags and pseudo-elements.
For example, the selector #header .nav li has a higher specificity than just .nav li.
Example:
#header .nav li {
color: red; /* higher specificity */
}
.nav li {
color: blue;
}
In this case, the color will be red because the selector with ID has greater specificity.