Home >Web Front-end >CSS Tutorial >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; }
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; }
HTML:
Spoiler: <span>
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; }
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!