CSS
How to style siblings elements using CSS hover
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
This article summarizes how to style siblings elements (elements aligned in parallel) using CSS hover.
PR
In this example, when hovering over the second element, colors are applied to the third, fourth, and fifth elements.
Screen after hover is here
Code when hovering
HTML
<div class="test1">test</div>
<div class="test2">test2</div>
<div class="test3">test3</div>
<div class="test4">test4</div>
<div class="test5">test5</div>
CSS
/* Self */
.test2:hover {
color: blue;
font-size: 30px;
}
/* Sibling below by 1 */
.test2:hover + .test3 {
color: orange;
}
/* Sibling below by 2 */
.test2:hover ~ .test4 {
color: pink;
}
Explanation
Elements written one below at the same level (sibling elements: younger sibling below 1) are written with +.
.test2:hover + .test3 {
color: orange;
}
Elements that are 2 or more elements apart (sibling elements: younger sibling below 2 or more) are written with ~.
.test2:hover ~ .test4 {
color: pink;
}
Codes that do not work
/* This does not work */
/* .test2:hover ~ .test1 {
font-size: 20px;
color: red;
} */
/* Cannot figure out how to apply changes from 2 to 1... */
/* This also does not work */
/* .test2:hover + .test5 {
color: green;
} */
Conclusion
That's it.
Currently seeking ways to apply changes with CSS hover to siblings elements one step away.
Please contact via Twitter DM for feedback or complaints.
Thank you!
Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!