Open In App

How to Add Onclick Effect using CSS ?

Last Updated : 06 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

HTML




<!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?

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.

HTML




<!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?

Can I have an onclick effect in CSS?



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads