Home > Web Front-end > CSS Tutorial > How Can I Keep a CSS Hover State Active After the Mouse Leaves the Element?

How Can I Keep a CSS Hover State Active After the Mouse Leaves the Element?

Mary-Kate Olsen
Release: 2024-12-24 12:20:15
Original
180 people have browsed it

How Can I Keep a CSS Hover State Active After the Mouse Leaves the Element?

Maintaining CSS Hover State After "Unhovering"

In web design, the hover state is often used to reveal additional content or effects upon hovering over an element. However, this state usually disappears when the mouse pointer leaves the element. This article explores a CSS solution to maintain the hover state even after "unhovering."

The Issue

Many beginners encounter the challenge of preserving the hover state. For instance, consider the following example code:

#about:hover #onabout {
  display: block;
}
Copy after login

When hovering over the #about element, the #onabout element becomes visible. However, it vanishes as soon as the hover state ends.

CSS Solution

Fortunately, CSS provides a solution using transition-delay. This property specifies the time to wait before applying CSS transitions. By setting it to a non-zero value, we can hold the hover state for a while after unhovering.

div img {
  transition: 0s 180s;
  opacity: 0;
}

div:hover img {
  opacity: 1;
  transition: 0s;
}
Copy after login

This code ensures that the image (img) remains visible for 180 seconds after unhovering.

Alternative Approach

Another CSS technique involves using transform and focus to fade out the image after clicking.

div:hover img:focus {
  transition: 3s;
  opacity: 0;
  transform: rotate(-360deg) scale(0.23);
}
Copy after login

This approach requires adding tabindex to the element in the HTML markup and clicking on the image to trigger the fading effect.

By employing these CSS techniques, you can maintain the hover state even after unhovering, enhancing the user experience on your webpages.

The above is the detailed content of How Can I Keep a CSS Hover State Active After the Mouse Leaves the 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template