Home > Web Front-end > CSS Tutorial > How to Easily Change an Image on Click with CSS?

How to Easily Change an Image on Click with CSS?

Linda Hamilton
Release: 2024-11-19 17:38:02
Original
1169 people have browsed it

How to Easily Change an Image on Click with CSS?

Change an Image on Click with Ease

Tired of the complex JS code required to change an image on click? Explore a simpler solution using pseudo selectors or the .active class.

Understanding the Solution

To change an image on click without extensive JS code, you can leverage the following techniques:

  • Pseudo Selectors: You can create a pseudo selector that targets the element on click and styles it with a different image using CSS.
  • .active Class: By applying the .active class to the target element on click, you can use CSS to display the desired image.

Implementing the Solution

Using Pseudo Selectors:

li:hover img, li:active img {
    display: none;
}

li:hover img#new_image, li:active img#new_image {
    display: block;
}
Copy after login

Using .active Class:

  1. Add the .active class to the target list element: li.active.
  2. Define the CSS rule for this class:
li.active img {
    display: none;
}

li.active img#new_image {
    display: block;
}
Copy after login

Example Code with .active Class:

<ul>
  <li><img>
Copy after login

Note: Remember to add the appropriate click event listener or use inline onclick attributes to trigger the change.

The above is the detailed content of How to Easily Change an Image on Click with 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