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

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.
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;
}




If this was helpful, we 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
Rakuten Ichiba
Yahoo! Shopping
PR