[CSS] Selectors to specify elements "before," "prior to," or "immediately before" a specific element
![[CSS] Selectors to specify elements](img/ogp.png)
Here's how to write selectors to specify elements before, prior to, or immediately before a specific element in CSS.
We'll use sibling combinator `~`, negation `:not()`, pseudo-class `:has()`, and more to specify them.
HTML
We'll use this common HTML structure.
<ul>
<li>リスト</li>
<li>リスト</li>
<li>リスト</li>
<li class="target">特定の要素</li>
<li>リスト</li>
<li>リスト</li>
</ul>
Table of Contents
Specific element "before"
Here's how to specify elements before a specific element.
Using `:not()`, we negate `li` elements that come after `.target`.
ul li:not(.target ~ li) {
color: red;
}
The `li` elements before and including `.target` are now red.
- List item
- List item
- List item
- Specific element
- List item
- List item
Specific element "prior to"
Here's how to specify elements prior to a specific element.
We add `:not(.target)` to the previous selector to also negate `.target` itself.
ul li:not(.target ~ li):not(.target) {
color: red;
}
The `li` elements prior to `.target` are now red.
- List item
- List item
- List item
- Specific element
- List item
- List item
Specific element "immediately before"
Here's how to specify the element immediately before a specific element.
Using `:has()`, we specify `li` elements that have `.target` as an adjacent sibling.
ul li:has(+ .target) {
color: red;
}
The `li` element immediately before `.target` is now red.
- List item
- List item
- List item
- Specific element
- List item
- List item
However, please note that `:has()` is not supported in FireFox as of 2023.




If this was helpful, we'd appreciate your support!
Any support received will be used for childcare.
Or support us by buying something from the buttons below
(You don't have to buy the linked product.)
Amazon
楽天市場
Yahoo!ショッピング
PR