Selectors and Specificity
25 minCSS selectors are the tools you use to target specific HTML elements for styling. They range from simple element selectors (like `h1`) to complex combinations that target elements based on their attributes, position, or relationship to other elements.
The three most common types are Element selectors (target tags), Class selectors (target `.classname`), and ID selectors (target `#idname`). Classes are reusable, while IDs should be unique to a page.
Specificity is the weight given to a CSS rule. It determines which style wins when multiple rules target the same element. For example, an ID selector is more specific (has more weight) than a class selector, which is more specific than an element selector.
Understanding specificity is crucial for debugging. If your styles aren't applying as expected, it's often because a more specific rule is overriding them. This is often referred to as 'specificity wars'.
Key Concepts
- Selectors determine what gets styled.
- Classes (`.`) are for groups; IDs (`#`) are for unique elements.
- Specificity is a scoring system for conflict resolution.
- The Universal selector (`*`) targets everything.
- Grouping selectors (`,`) applies styles to multiple elements.
Learning Objectives
Master
- Using Element, Class, and ID selectors
- Calculating specificity scores
- The hierarchy of CSS selectors
- When to use classes vs. IDs
Develop
- Strategic planning for CSS architecture
- Debugging conflicting styles
- Writing efficient, reusable selectors
Tips
- Rely mainly on Class selectors for styling.
- Avoid using IDs for styling due to their high specificity.
- Keep selectors simple; avoid deep nesting.
- Use the browser's developer tools to inspect specificity.
Common Pitfalls
- Overusing `!important` to force styles (this breaks the cascade).
- Using overly complex selectors that are hard to read.
- Confusing the syntax for classes (`.`) and IDs (`#`).
- Assuming order doesn't matter (later rules override earlier ones if specificity is equal).
Summary
- Selectors are how you target elements.
- Specificity determines which rule wins.
- Classes are the workhorse of CSS styling.
- Avoid specificity wars by keeping selectors low-weight.
Exercise
Create a class selector to style a specific element with a red background.
.highlight {
background-color: red;
}
Exercise Tips
- Try using an ID selector and compare specificity with the class selector.
- Add text color to ensure good contrast with the red background.
- Experiment with different background properties (background-image, background-size).
- Use browser DevTools to see how specificity affects which styles apply.