🎨
Advanced CSS Selectors
Advanced
120 XP
40 min
Lesson Content
Advanced CSS Selectors
Advanced selectors allow you to target elements with precision, making your CSS more efficient and maintainable.
Attribute Selectors
/* Exact match */
input[type="text"] { }
/* Contains value */
a[href*="example"] { }
/* Starts with */
a[href^="https"] { }
/* Ends with */
img[src$=".jpg"] { }
/* Contains word */
p[class~="important"] { }
/* Has attribute (any value) */
input[disabled] { }Combinators
/* Descendant (space) - Any descendant */
div p { }
/* Child (>) - Direct child */
div > p { }
/* Adjacent sibling (+) - Immediately following */
h2 + p { }
/* General sibling (~) - Following siblings */
h2 ~ p { }Structural Pseudo-classes
/* First child */
p:first-child { }
/* Last child */
p:last-child { }
/* Nth child */
p:nth-child(3) { } /* 3rd child */
p:nth-child(odd) { } /* Odd children */
p:nth-child(even) { } /* Even children */
p:nth-child(3n) { } /* Every 3rd */
p:nth-child(3n+1) { } /* 1st, 4th, 7th... */
/* Nth of type */
p:nth-of-type(2) { } /* 2nd paragraph */
/* Only child */
p:only-child { }
/* Empty */
p:empty { }Logical Selectors
/* Not selector */
p:not(.special) { }
/* Is selector (matches any) */
:is(h1, h2, h3) { }
/* Where selector (specificity 0) */
:where(h1, h2) { }
/* Has selector (parent selector) */
div:has(p) { } /* div that contains p */Selector Specificity
Understanding specificity helps resolve conflicts:
- Inline styles: 1000
- IDs: 100
- Classes, attributes, pseudo-classes: 10
- Elements, pseudo-elements: 1
Best Practices
- Use specific selectors to avoid conflicts
- Prefer classes over complex selectors for maintainability
- Use attribute selectors for form styling
- Combinators help create scoped styles
Example Code
Style elements using attribute selectors, combinators, and structural pseudo-classes.
<!DOCTYPE html>
<html>
<head>
<style>
/* Style all input[type="text"] with blue border */
/* Style direct children of .container with padding */
/* Style every 2nd paragraph with different background */
/* Style links that start with "https" */
</style>
</head>
<body>
<div class="container">
<input type="text" placeholder="Text input">
<input type="email" placeholder="Email input">
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>
</div>
<a href="https://example.com">HTTPS Link</a>
<a href="http://example.com">HTTP Link</a>
</body>
</html>Expected Output:
Styled elements using advanced selectors
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code