Home > Mobile >  How to close this image with CSS?
How to close this image with CSS?

Time:10-29

I'm trying to close and open an image on HTML with a click on a button but it's not working.

There's my code:

.cover {
  position: sticky;
  display: flex;
  align-items: flex-start;
  height: 275.25px;
  width: 275.25px;
}

@keyframes closeCover {
  0% {
    height: 275.25px;
  }
  100% {
    height: 0px;
  }
}

.cover:active {
  animation: closeCover 1s linear forwards;
}
<div >
  <img src="./images/arrow.svg" alt="close cover" id="close">
  <a href=""><img src="./images/Fiure-de-vie.jpg" alt="cover" id="cover"></a>
</div>

I'm trying to close and open an image with HTML/CSS.

CodePudding user response:

You need to disable the overflow of the image. Also, the image should be 100% the width of its parent. Also, the trigger anchor tag is in the container that closes, so you must move it away. And I used a simple JS function to add a class to open and close it.

So essentially it should look like this:

const cover = document.querySelector(".cover");

function func() {
  cover.classList.toggle('closed');
  console.log('toggled', cover.classList)
}
.cover {
  position: sticky;
  display: flex;
  align-items: flex-start;
  height: 275.25px;
  width: 275.25px;
  overflow: hidden;
}

.cover img {
  width: 100%;
}

.close-btn {
  position: relative;
}

@keyframes closeCover {
  0% {
    height: 275.25px;
  }
  100% {
    height: 0px;
  }
}

.cover.closed {
  animation: closeCover 1s linear forwards;
}
<div>
  <div >
    <img src="https://media.istockphoto.com/vectors/thumbnail-image-vector-graphic-vector-id1147544807?k=20&m=1147544807&s=612x612&w=0&h=pBhz1dkwsCMq37Udtp9sfxbjaMl27JUapoyYpQm0anc=" alt="close cover" id="close">
  </div>
  <a href="#"  onClick="func()">close</a>
</div>

CodePudding user response:

Move the image inside a label with overflow: hidden. then connect to the label an input type="checkbox" that can have a checked-state:

.cover {
  position: sticky;
  display: flex;
  align-items: flex-start;
  height: 275.25px;
  width: 275.25px;
}

/* hides the checkbox */
.cover input {
  display: none;
}

.cover label {
  overflow: hidden;
}

#img:checked   label {
  animation: closeCover 1s linear forwards;
}

@keyframes closeCover {
  0% {
    height: 275.25px;
  }
  100% {
    height: 0px;
  }
}
<div >
  <input type="checkbox" id="img">
  <label for="img"><img src="https://via.placeholder.com/100.jpg"></label>
</div>

  • Related