Advanced Selectors
35 minOnce you master basic selectors, Advanced Selectors give you surgical precision in targeting elements. These include Attribute selectors, Structural pseudo-classes, and Combinators.
**Attribute Selectors** target elements based on the presence or value of an HTML attribute (e.g., `input[type='submit']` or `a[href^='https']` for secure links).
**Structural Pseudo-classes** like `:nth-child()`, `:first-of-type`, and `:not()` allow you to select elements based on their position in the DOM tree or by exclusion. `:nth-child(2n)` is a classic way to stripe tables.
**Combinators** define relationships: Direct child (`>`), Adjacent sibling (`+`), and General sibling (`~`). These allow you to style elements based on what is next to them or inside them.
Key Concepts
- Attribute selectors target HTML attributes.
- `:nth-child()` selects by pattern/index.
- `:not()` excludes elements.
- Combinators (`>`, `+`, `~`) define relationships.
- Precision targeting reduces the need for classes.
Learning Objectives
Master
- Using attribute matching operators (^=, $=, *=)
- Mastering nth-child formulas (odd, even, an+b)
- Using the negation pseudo-class :not()
- Understanding sibling combinators
Develop
- Writing concise, powerful CSS rules
- Handling dynamic content where classes might be missing
- Cleaning up HTML by removing presentational classes
Tips
- Use `* + *` (the 'lobotomized owl') to add margin between flow elements.
- Use `[class^='icon-']` to style all icon classes at once.
- Use `:not(:last-child)` to add borders/margins to list items except the last one.
- Test complex selectors in the browser console first.
Common Pitfalls
- Assuming `:nth-child(1)` is always the element you want (it counts *all* siblings).
- Over-complicating selectors making them hard to read.
- Performance impact of very complex universal selectors (rare but possible).
- Browser compatibility for very new pseudo-classes (check CanIUse).
Summary
- Advanced selectors offer precise control.
- Attribute selectors match HTML properties.
- Structural classes match position/order.
- Combinators match relationships between nodes.
Exercise
Use an attribute selector to style all input elements with type 'text'.
input[type="text"] {
border: 2px solid #ccc;
border-radius: 4px;
padding: 8px;
}
Exercise Tips
- Try attribute selectors with patterns: input[type^='text'] for types starting with 'text'.
- Use :nth-child(odd) to style alternating rows in a table.
- Combine selectors: input[type='text']:not(:disabled) to target only enabled text inputs.
- Use sibling combinators: h2 + p to style paragraphs immediately after h2 headings.