Search code examples
css

Zoom in and out on mouse click with CSS


I want to zoom image with only CSS. The code below zooms the image when the left button of the mouse is kept pressed but I want to zoom in and out with a mouse click. How can I achieve that?

.container img {
  transition: transform 0.25s ease;
  cursor: zoom-in;
}

.container img:active {
  -webkit-transform: scale(2);
  transform: scale(2);
  cursor: zoom-out;
}

Solution

  • Let's use a trick here, an input checkbox:

    input[type=checkbox] {
      display: none;
    }
    
    .container img {
      margin: 100px;
      transition: transform 0.25s ease;
      cursor: zoom-in;
    }
    
    input[type=checkbox]:checked ~ label > img {
      transform: scale(2);
      cursor: zoom-out;
    }
    <div class="container">
      <input type="checkbox" id="zoomCheck">
      <label for="zoomCheck">
        <img src="https://via.placeholder.com/200">
      </label>
    </div>