Home > Web Front-end > CSS Tutorial > How Can I Use CSS to Apply Hover Effects to Multiple Elements Simultaneously?

How Can I Use CSS to Apply Hover Effects to Multiple Elements Simultaneously?

Mary-Kate Olsen
Release: 2024-11-27 07:46:10
Original
352 people have browsed it

How Can I Use CSS to Apply Hover Effects to Multiple Elements Simultaneously?

Hover on Element, Effects on Multiple Elements in CSS

In HTML layout, you may encounter a scenario where hovering over an element should trigger effects on multiple related elements. Consider the following HTML code:

<div class="section">
  <div class="image"><img src="myImage.jpg" /></div>
  <div class="layer">Lorem Ipsum</div>
</div>
Copy after login

Both the "image" and "layer" classes have borders with different colors for their normal and hover states. The goal is to have the border color change on both elements when hovering over the "layer" element and vice versa.

CSS Solution:

Achieving this effect without JavaScript is possible using CSS. Here's an example:

HTML:

<div class="section">
    <img src="myImage.jpg" />
    <div class="layer">Lorem Ipsum</div>
</div>
Copy after login

CSS:

.section {
    background: #ccc;
}

.layer {
    background: #ddd;
}

.section:hover img {
    border: 2px solid #333;
}

.section:hover .layer {
    border: 2px solid #F90;
}
Copy after login

Explanation:

  • The ".section:hover img" selector specifies that when the ".section" element is hovered over, the "img" element within it should have a 2px solid border with the color #333.
  • Similarly, the ".section:hover .layer" selector targets the ".layer" element within the ".section" and changes its border color to #F90 on hover.

This CSS ensures that when you hover over the "layer" element, both the "image" and "layer" elements will have their border colors updated, creating the desired effect without any scripting.

The above is the detailed content of How Can I Use CSS to Apply Hover Effects to Multiple Elements Simultaneously?. 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