0

I have a checkbox and an image on an HTML page:

I want the image to disappear when the checkbox is checked, and return back when it's unchecked. It can be easily done with the opacity property but this will only hide the image – and I need it to disappear (so that other elements can take the image's place for example). I tried to combine opacity with display properties:

img {
    display: block;
    opacity: 1;
    transition: opacity 0.5s ease-in-out;
}
#checkbox:checked ~ div img {
    display: none;
    opacity: 0;
}
<body>
    <input type="checkbox" id="checkbox">
    <div>
        <img src="https://via.placeholder.com/150" alt="">
    </div>
</body>

but it wouldn't work (no transition).

How can I solve this problem?

Jax-p
  • 7,225
  • 4
  • 28
  • 58
Zoe
  • 19
  • 1
  • 1

1 Answers1

2

display property cannot be transitioned nor animated. It works fine without it.

img {
    opacity: 1;
    transition: opacity 0.5s ease-in-out;
}
#checkbox:checked ~ div img {
    opacity: 0;
}
<body>
    <input type="checkbox" id="checkbox">
    <div>
        <img src="https://via.placeholder.com/150" alt="">
    </div>
</body>

You check another question for more information.


In case you need that space you can animate for example height or max-height.

img {
    opacity: 1;
    max-height: 150px;
    transition: opacity 0.5s ease-in-out, max-height 0.5s ease-in-out;
}
#checkbox:checked ~ div img {
    opacity: 0;
    max-height: 0;
}
<body>
    <input type="checkbox" id="checkbox">
    <div>
        <img src="https://via.placeholder.com/150" alt="">
    </div>
</body>
Jax-p
  • 7,225
  • 4
  • 28
  • 58
  • _“It works fine without it”_ - the question was specifically about hiding the element in a way so that it does not take up space any more, and that does _not_ “work fine” with just opacity. – CBroe Dec 11 '20 at 08:56
  • @CBroe You did not specified explicit request. What would you expect it to do? Animate opacity and _disappear_ (free space) at the same time is not possible - How it should look like? You might use `height` or `translate` or whatever but _not take up space_ is not animation. – Jax-p Dec 11 '20 at 08:59
  • It’s not my question. _“Animate opacity and disappear (free space) at the same time is not possible”_ - I’m guessing, animate opacity first, disappear after when that is done? – CBroe Dec 11 '20 at 09:06