Selecting a preceding element using :has()
What was impossible before is now possible. The functional :has() CSS pseudo-class represents an element if any of the relative selectors that are passed as an argument match at least one element when anchored against an element. This pseudo-class presents a way of selecting a parent element or a previous sibling element with respect to a reference element by taking a relative selector list as an argument.
/* Selects an h1 heading with a
paragraph element that immediately follows
the h1 and applies the style to h1 */
h1:has(+ p) {
margin-bottom: 0;
}
If you're concerned with browser support, you can use the following feature query.
@supports selector(:has(+ *)) {
h1:has(+ p) {
margin-bottom: 0;
}
}
For web developers and designers, it's crucial to stay updated on what CSS can and cannot do, which ultimately enables crafting better web experiences. Keep experimenting, keep learning, and continue pushing the boundaries of what you can achieve with CSS.