How to Add an Onclick Effect in 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 attach a <label> to the “checkbox” input type through the “for” attribute of the <label> tag.

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: #666;
      }
    </style>
  </head>
  <body>
    <input type="checkbox" id="box" />
    <label for="box">Click here</label>
  </body>
</html>

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 a button onclick effect:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #btnControl {
        display: none;
      }
      .btn {
        width: 80px;
        height: 30px;
        background: #fff;
        border-radius: 7px;
        padding: 1px 3px;
        box-shadow: 1px 1px 1px #000;
        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 #000;
        -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>

Do you find this helpful?

Related articles