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

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

Patricia Arquette
Release: 2024-12-02 14:04:10
Original
327 people have browsed it

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

How to Change the Color of Sibling Elements on Hover in CSS

In HTML, siblings are elements that share the same parent element. When hovering over specific elements, it's often desirable to change the appearance of their sibling elements.

Changing the Color of a Following Sibling Element

To change the color of a sibling element that follows the hovered element, use the adjacent sibling selector ( ) in CSS. For instance, to change the color of a following element when the preceding

element is hovered:

h1 {
  color: #4fa04f;
}

h1 + a {
  color: #a04f4f;
}

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

Limitation: Changing the Color of a Preceding Sibling Element

CSS does not provide a direct way to change the style of a preceding sibling element based on the hover state of its sibling.

Using a Wrapper Div

Wrapping the elements in a div with an ID allows you to change the color of the preceding sibling using more complex CSS selectors.

<div>
Copy after login
#banner h1 {
  color: #4fa04f;
}

#banner a {
  color: #a04f4f;
}

#banner h1:hover a {
  color: #4f4fd0;
}

#banner:hover a {
  color: #a04f4f;
}
Copy after login

This approach allows for greater control over the styling of sibling elements, but it introduces additional markup and can be less efficient.

The above is the detailed content of How Can I Change the Color of Sibling HTML 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