Open In App

How to Add Onclick Effect using CSS ?

In this article, we will see how to add onclick effect using CSS. To add the onclick effect using CSS, we can use :active pseudo selector.

When an element is clicked, the onclick JavaScript event is launched. JavaScript is required to add an event listener to the HTML element and then run some code when the element is clicked in order to produce an onclick effect.



Example 1: However, when a button is clicked, CSS allows you to alter the background color.




<!DOCTYPE html>
<html>
  
<head>
    <title>Page Title</title>
  
    <style>
        button {
            background-color: blue;
            color: white;
            padding: 10px;
            border: none;
            cursor: pointer;
        }
  
        button:active {
            background-color: red;
        }
    </style>
</head>
  
<body>
    <h2>Welcome To GFG</h2>
    <button>Click me</button>
</body>
  
</html>

Output:



Can I have an onclick effect in CSS?

When the button is clicked, its background color changes from blue to red, creating an “onclick” effect.

Example 2: When the box is clicked, it shrinks slightly in size due to the transform property applied to it, creating an “onclick” effect.




<!DOCTYPE html>
<html>
  
<head>
    <title>Page Title</title>
  
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: blue;
            cursor: pointer;
        }
  
        .box:active {
            transform: scale(0.9);
        }
    </style>
</head>
  
<body>
    <h2>Welcome To GFG</h2>
    <div class="box"></div>
</body>
  
</html>

Output:

Can I have an onclick effect in CSS?


Article Tags :