Front-End & Daily

【CSS】Selectors to specify elements "after", "from now on", or "immediately after" a specific element

【CSS】Selectors to specify elements

Here's how to write CSS selectors to specify elements after, from now on, or immediately after a specific element.

Basically, this method uses the fundamental CSS selectors ~(general sibling combinator) and +(adjacent sibling combinator).

We also introduce the "reverse" application of these.

【CSS】Selectors to specify elements

【CSS】Selectors to specify elements "before", "earlier than", or "immediately before" a specific element

HTML

We will use this HTML in common.

<ul>
	<li>リスト</li>
	<li>リスト</li>
	<li>リスト</li>
	<li class="target">特定の要素</li>
	<li>リスト</li>
	<li>リスト</li>
</ul>

Table of Contents

Elements "after" a specific element

To specify elements after a specific element, do this.

ul li.target ~ li {
	color: red;
}

This is basic CSS, but linking with "~" means "parallel elements after that".

The "li" elements after ".target" are now red.

  • List
  • List
  • List
  • Specific element
  • List
  • List

If the element after ".target" is not necessarily an "li", write it like this.

.target ~ * {
	color: red;
}

Elements "from now on" a specific element

To specify elements from now on a specific element, do this.

In addition to the previous method, we also add the .target itself.

ul li.target,
ul li.target ~ li {
	color: red;
}

The "li" elements from ".target" onwards are now red.

  • List
  • List
  • List
  • Specific element
  • List
  • List

If the elements from ".target" onwards are not necessarily "li", write it like this.

.target,
.target ~ * {
	color: red;
}

Elements "immediately after" a specific element

To specify the element immediately after a specific element, do this.

ul li.target + li {
	color: red;
}

This is also basic CSS, but linking with "+" means "the next element".

The "li" element immediately after ".target" is now red.

  • List
  • List
  • List
  • Specific element
  • List
  • List

If the element immediately after ".target" is not necessarily an "li", write it like this.

.target + * {
	color: red;
}

Comments

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

Enter your name and email address

Enter if you would like a reply by email.

The personal information provided will not be disclosed. It will only be used for replies.

It will be sent directly. Please confirm and "Send".

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

Send support via OFUSE


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

Amazon

Rakuten Ichiba

Yahoo! Shopping

PR

As an Amazon Associate, "けん" earns from qualifying purchases.

Share

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