Home > Web Front-end > CSS Tutorial > How Can I Change the Color of Sibling Elements on Hover Using CSS?

How Can I Change the Color of Sibling Elements on Hover Using CSS?

Mary-Kate Olsen
Release: 2024-12-13 05:49:18
Original
224 people have browsed it

How Can I Change the Color of Sibling Elements on Hover Using CSS?

How to Change Color of Sibling Elements on Hover with CSS

In HTML, it's common to have elements that are siblings, meaning they share the same parent element. When you hover over a specific element, you may want to modify the appearance of its sibling elements. However, CSS has limitations when it comes to styling previous siblings.

Solution:

CSS allows you to target sibling elements that follow the hovered element. For instance:

h1 {
    color: #4fa04f;
}
h1 + a {
    color: #a04f4f;
}
Copy after login

This code sets the color of the first

heading to green and the adjacent link to red.

To change the color of the link when hovering over the

heading, add the :hover pseudo-class:

h1:hover + a {
    color: #4f4fd0;
}
Copy after login

Note:

Changing the color of previous siblings is not possible with CSS. If you want to style a previous sibling, consider using JavaScript or a CSS framework that provides additional functionality.

Example with a Wrapper Element:

Wrapping the elements in a container (<div>) with an ID won't change the CSS rules. You would still follow the same principles as described above:

<div>
Copy after login
#banner h1 {
    color: #4fa04f;
}
#banner h1 + a {
    color: #a04f4f;
}
#banner h1:hover + a {
    color: #4f4fd0;
}
Copy after login

The above is the detailed content of How Can I Change the Color of Sibling Elements on Hover Using CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template