2

I think the best example of what I am thinking of would be like you click on an image and it changes the filter and that filter stays even if you're not holding down on the image.

At first I thought maybe I could use the :active pseudo-class on an image to make it grayscale upon click as a test however it didn't work. Then I tried making the image a link and doing

a:visited {
    filter:  grayscale(100%);
}

however, it did not work.

6
  • :active requires the mouse button down and :visited only permits a limited range of properties to apply. Commented Feb 8, 2024 at 19:20
  • Please don't add meta-commentary like asking questions about votes to your question. The question should stay focused on you actual question. You can use Meta Stack Overflow to ask questions about your question, but it carries the risk of bringing more attention to your question. Commented Feb 8, 2024 at 19:26
  • Damn. Is there anyway to make it so if I click an element it changes something permanently until the page is refreshed using purely css/html? Commented Feb 8, 2024 at 19:26
  • 2
    You could wrap the element in a label for an <input type="checkbox"> and style it using :checked Commented Feb 8, 2024 at 19:28
  • 1
    FWIW, please note that any scenario in which you sort of "hack" HTML to use non-semantic elements to achieve some behavior might result in deleterious effects to accessibility and SEO. Depending on what you're doing this may or not be the case, but it seems like a potential outcome. Commented Feb 8, 2024 at 19:30

2 Answers 2

2

You can't do that by pure CSS, but you can use a hidden checkbox to manipulate the image.

input.hidden {
  display: none;
}

label > img {
  transition: filter 300ms;
  cursor: pointer;
}

input[type="checkbox"]:checked ~ label > img {
  filter: grayscale(1);
}
<div>
  <input id="doggy" class="hidden" type="checkbox">
  <label for="doggy"><img src="https://picsum.photos/id/237/200/200"></label>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for a clever solution, but as I pointed out in a previous comment, it is worth noting for anyone looking to implement this solution that it will have deleterious affects on accessibility and potentially SEO if you don't take additional steps to prevent assistive technologies from reporting these things as form inputs.
1

Play with transition and you can simulate it:

img {
  transition: 0s 9999s filter; /* a big delay on mouseout so it take a lot of time to change */
  cursor: pointer;
}

img:active {
  transition: 0s filter; /* instant change on click */
  filter: grayscale(1);
}
<img src="https://picsum.photos/id/125/200/200">

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.