This content originally appeared on Bram.us and was authored by Bramus!
Leverage CSS :has()
to select all siblings between to boundaries.
~
# Creating a Sibling Scope
Say you have markup like this:
<ul>
<li>outside</li>
<li class="upper">upper</li>
<li>inside</li>
<li>inside</li>
<li>inside</li>
<li>inside</li>
<li class="lower">lower</li>
<li>outside</li>
</ul>
If you want to select all elements between that .upper
and .lower
element, you can do so using this selector powered by the almighty :has()
selector:
.upper ~ :has(~ .lower) {
outline: 1px solid red;
}
It works as follows:
.upper ~ *
will select all elements that are preceded by.upper
.:has(~ .lower)
will select all elements that are followed by a.lower
.- By combining both, you can clamp the selection and create a scope between the
.upper
and.lower
siblings.
~
# Demo
See the Pen Sibling Scopes by Bramus (@bramus) on CodePen.
~
# Limitations
As shown in the demo, the .upper ~ :has(~ .lower)
is greedy. If you have two adjacent sets of boundaries that are also siblings from each other, the selector will select everything in between the first .upper
up to the last .lower
.
<ul>
<li>outside</li>
<li class="upper">upper</li>
<li>inside</li>
<li>inside</li>
<li class="lower">lower</li>
<li class="upper">upper</li>
<li>inside</li>
<li>inside</li>
<li class="lower">lower</li>
<li>outside</li>
</ul>
~
# Browser Support
These selectors are supported by all browsers that have :has()
support. At the time of writing this does not include Firefox.
👨‍🔬 Flipping on the experimental :has()
support in Firefox doesn’t do the trick either. Its implementation is still experimental as it doesn’t support all types of selection yet. Relative Selector Parsing (i.e. a:has(~ b)
) is one of those features that’s not supported yet – Tracking bug: #1774588
~
# Spread the word
To help spread the contents of this post, feel free to retweet its announcement tweet:
Sibling Scopes in CSS, thanks to :has()
🏷 #css #selectors pic.twitter.com/qdtOuwgLzm
— Bram.us (@bramusblog) January 12, 2023
~
🔥 Like what you see? Want to stay in the loop? Here's how:
This content originally appeared on Bram.us and was authored by Bramus!

Bramus! | Sciencx (2023-01-12T00:05:24+00:00) Sibling Scopes in CSS, thanks to :has(). Retrieved from https://www.scien.cx/2023/01/12/sibling-scopes-in-css-thanks-to-has/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.