Advanced selectors

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the css-and-design category.

Last Updated: 2024-05-04

Advanced Selectors

A good reference is here

Select children arbitrarily deep in another selector

.parent .child /* all .child els under .parent */
.parent h2 /* all h2 els under .parent /

Select children that are direct children only (i.e. one-level deep and no more)

.parent > .child /* all .child els directly under .parent */
.parent > h2 /* all h2 els directly under .parent /

Select sibling elements that share the same parent (without specifying the parent) and COME AFTER the target sibling (the first argument to tilde). Because of this "come after bit" this means potentially not all siblings will be selected.

.sibling-target ~ .siblingb /* all .siblingb els that follow .sibling-target and share the same parent */
.sibling-target ~ h2 /* all h2 els that COME AFTER .sibling-target and share the same parent /

Select a sibling directly following another element

.sibling-target + p /* select the 1st p element after .sibling-target that is a sibling */
h2 + p /* select the 1st p element after h2 that is a sibling */

Select an element containing an attribute (e.g. <a href="" target=""></a> has two attributes, href and target

a[target] /* any a element with the target attribute */

Select an element where the attribute contains a specific value (e.g. <a href="www.example.com"> - href has value www.example.com)

a[href="www.example.com"] /* any a element with the href attribute equal to 'www.example.com' */