How to Add an Onclick Effect with HTML and CSS

Solutions with HTML and CSS

The most common way of creating a click event with CSS is using the checkbox hack. This method has broad browser support. You need to add a for attribute to the <label> element and an id attribute to the <input> element.

Example of adding an onclick event by using the checkbox hack:

<!DOCTYPE html>
<html>
  <head>
    <style>
      label {
        display: block;
        background: #dbdbd9;
        width: 80px;
        height: 80px;
      }
      #box:checked + label {
        background: #fffc47;
        color: #666666;
      }
    </style>
  </head>
  <body>
    <form action="/form/submit" method="post">
      <input type="checkbox" id="box" />
      <label for="box">Click here</label>
    </form>
  </body>
</html>

Result

In the example above, we applied the same value both to the id attribute of the <input> tag and for attribute of the <label> tag. The label onclick is restyled with the :checked pseudo-class.

Example of adding an onclick event for resizing the image:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #btnControl {
        display: none;
      }
      #btnControl:checked + label > img {
        width: 150px;
        height: 170px;
      }
    </style>
  </head>
  <body>
    <input type="checkbox" id="btnControl" />
    <label class="btn" for="btnControl">
      <img src="https://images.unsplash.com/photo-1565520651265-1148c3b277f4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" id="btnLeft" />
    </label>
  </body>
</html>

Since a <label> element can be associated only with one form control, you cannot just place a button inside the <label> tag. But you can add some CSS to change the appearance and behavior of the button.

Example of adding an onclick effect on the <input> tag:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #btnControl {
        display: none;
      }
      .btn {
        width: 80px;
        height: 30px;
        background: #ffffff;
        border-radius: 7px;
        padding: 1px 3px;
        box-shadow: 1px 1px 1px #000000;
        display: block;
        text-align: center;
        background-image: linear-gradient(to bottom, #e8e8e8, #a1a1a1);
        font-family: arial;
        font-size: 14px;
        line-height: 30px;
      }
      .btn:hover {
        background-image: linear-gradient(to bottom, #97e8ae, #3be36b);
      }
      .btn:active {
        margin-left: 1px 1px 0;
        box-shadow: -1px -1px 1px #000;
        outline: 1px solid #000000;
        -moz-outline-radius: 7px;
        background-image: linear-gradient(to top, #97e8ae, #3be36b);
      }
      #btnControl:checked + label {
        width: 70px;
        height: 74px;
        line-height: 74px;
      }
    </style>
  </head>
  <body>
    <input type="checkbox" id="btnControl" />
    <label class="btn" for="btnControl">Click here</label>
  </body>
</html>