Open In App

How to Add Onclick Effect using CSS ?

Last Updated : 07 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

In this article, we’ll explore how to create an onclick effect using CSS. While the onclick event is generally associated with JavaScript, about 30–40% of basic visual feedback effects—such as color changes, button presses, or shadow effects—can be achieved using CSS alone through the :active pseudo-class.

The :active selector applies styles to an element while it is being clicked, allowing you to simulate a click effect without any JavaScript. However, for more advanced interactions or logic-driven behavior, JavaScript is still required.

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

index.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.

index.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?

How to Add Onclick Effect using CSS ?

Similar Reads