Home > Web Front-end > CSS Tutorial > Why Doesn't My Hover Effect Work on Elements with `visibility: hidden` in CSS?

Why Doesn't My Hover Effect Work on Elements with `visibility: hidden` in CSS?

Barbara Streisand
Release: 2024-11-12 01:26:03
Original
880 people have browsed it

Why Doesn't My Hover Effect Work on Elements with `visibility: hidden` in CSS?

Visibility Not Working in CSS: Here's Why and How to Fix It

In CSS styling, ambiguity can sometimes lead to unexpected results. Let's explore a common issue faced when attempting to hide text with the 'visibility' property.

Problem:

Your CSS reads as follows:

.spoiler {
    visibility: hidden;
}

.spoiler:hover {
    visibility: visible;
}
Copy after login

According to this configuration, hovering over text with the '.spoiler' class should reveal it. However, this doesn't occur, leaving the text invisible regardless of the mouse position.

Reason:

The issue lies in the default behavior of hidden elements. Elements with 'visibility: hidden' are not recognized by the user agent during mouse events, including hover. Therefore, the hover state is never activated.

Solution 1: Nesting Elements

To overcome this challenge, one can nest the spoiler text within another element:

CSS:

.spoiler span {
    visibility: hidden;
}

.spoiler:hover span {
    visibility: visible;
}
Copy after login

HTML:

Spoiler: <span>
Copy after login

This solution works because the nested span element with the hidden visibility initially blocks mouse events. However, when the '.spoiler' parent element receives the hover event, it activates and reveals the span element, making the text visible.

Solution 2 (Chrome Only): Outline Trick

An alternative approach for Chrome is to add an outline to the '.spoiler' element:

.spoiler {
    outline: 1px solid transparent;
}
Copy after login

This technique creates an invisible hitbox that responds to mouse events, allowing hover effects to function properly on hidden elements.

The above is the detailed content of Why Doesn't My Hover Effect Work on Elements with `visibility: hidden` in 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