.class
and #id
work well for simple tasks, complex websites often require more sophisticated approaches. Advanced CSS selectors allow you to:
Selector Type | Example | Description |
---|---|---|
Attribute Contains | [attr*="value"] | Selects elements with an attribute containing “value” |
Attribute Starts With | [attr^="value"] | Selects elements with an attribute starting with “value” |
Attribute Ends With | [attr$="value"] | Selects elements with an attribute ending with “value” |
Not Selector | :not(selector) | Excludes elements that match the selector |
Nth-child | :nth-child(n) | Selects the nth child of its parent |
Nth-of-type | :nth-of-type(n) | Selects the nth sibling of its type |
Selector | Syntax | Description |
---|---|---|
Adjacent | A + B → h2 + p | Select p immediately after an h2 |
General Sibling | A ~ B → .a ~ .b | Select all .b siblings after .a |
Direct Child | A > B → ul > li | Select li that is a direct child of ul |
js_render
and use flexible selectors:
js_render: true
to see what the DOM actually contains
*
is slow; use more specific selectors. Use class (.class
) and ID (#id
) selectors over attribute selectors for speed..product-grid .product .title
is faster than body div.container div.products div.product-grid div.product div.title
#product-123
is faster than [data-product-id="123"]
>
) and adjacent (+
) selectors are faster than descendant selectors (space)Selector | Purpose | Example |
---|---|---|
element | Select by tag | div , span , h1 |
.class | Select by class | .product , .price |
#id | Select by ID | #main , #product-123 |
[attr] | Has attribute | [data-id] |
[attr="val"] | Exact attribute | [type="submit"] |
[attr*="val"] | Contains value | [href*="product"] |
[attr^="val"] | Starts with value | [class^="product-"] |
[attr$="val"] | Ends with value | [src$=".jpg"] |
:nth-child(n) | By position | li:nth-child(2) |
:first-child | First child | li:first-child |
:last-child | Last child | li:last-child |
:not(selector) | Negation | .item:not(.featured) |
A > B | Direct child | .product > .title |
A + B | Adjacent sibling | h2 + p |
A ~ B | General sibling | .featured ~ .product |
A, B | Multiple selectors | .price, .discount |
A B | Descendant | .product .price |