Front-End & Daily

[CSS] Selectors to specify elements "before," "prior to," or "immediately before" a specific element

[CSS] Selectors to specify elements

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.

Can I use

Comments

After reviewing the content, we will publish it, omitting any personal information.

Enter your name and email address too

Please enter if you would like a reply via email.

We will not disclose any personal information provided. It will only be used for replies.

It will be sent directly. Please confirm and then click 'Send'.

If this was helpful, we'd appreciate your support!
Any support received will be used for childcare.

Support on OFUSE


Or support us by buying something from the buttons below
(You don't have to buy the linked product.)

Amazon

楽天市場

Yahoo!ショッピング

PR

As an Amazon Associate, Ken earns from qualifying purchases.

Share

Share on Twitter Share on Facebook Share on LINE Share on Hatena Bookmark