Home > Web Front-end > CSS Tutorial > Can CSS Affect One Element's Opacity When Hovering Over a Different Element?

Can CSS Affect One Element's Opacity When Hovering Over a Different Element?

DDD
Release: 2024-12-09 17:43:11
Original
786 people have browsed it

Can CSS Affect One Element's Opacity When Hovering Over a Different Element?

Can Elements Influence Each Other When Hovering over Different Elements?

Problem:

The goal is to modify the opacity of one element (#thisElement) by hovering over another (img) without utilizing JavaScript.

Desired Functionality:

When hovering over 'img', the opacity of 'img' should increase to 100%, while the opacity of '#thisElement' should decrease to 30%.

CSS Limitations:

Unfortunately, CSS alone cannot achieve this effect because it lacks the capability to apply styles to an element based on the hovering of a different element.

Options for Affecting Neighboring Elements:

However, CSS can alter the style of elements related to the hovered element:

  • Descendants: Apply styles to child or nested elements. Example:

    #parent_element:hover #child_element {
      opacity: 0.3;
    }
    Copy after login
  • Adjacent Siblings: Affect elements immediately following or preceding the hovered element. Example:

    #first_sibling:hover + #second_sibling {
      opacity: 0.3;
    }
    Copy after login

Proposed Solution:

Based on the given HTML structure, where 'img' has siblings immediately below it without nesting, you can utilize the adjacent sibling selector:

img:hover + img {
    opacity: 0.3;
    color: red;
}
Copy after login

This CSS rule will adjust the opacity of the 'img' elements adjacent to the hovered 'img' element.

The above is the detailed content of Can CSS Affect One Element's Opacity When Hovering Over a Different Element?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template