Open In App

How to Add a Pressed Effect on Button Click in CSS?

Last Updated : 15 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To add a pressed effect on a button click using only CSS, you can use the :active pseudo-class, which applies styles when the button is clicked or tapped.

1. Using CSS transform Property

The CSS transform property enables you to adjust an element’s appearance by applying scaling, rotation, translation, or skewing effects. By leveraging the transform property, you can create a “pressed” effect on a button, making it look as though it’s being pushed down when clicked.

Syntax

transform: scale()
html
<!DOCTYPE html>
<html>

<head>
    <style>
        .btn {
            border: none;
            padding: 12px 40px;
            font-size: 16px;
            background-color: green;
            color: #fff;
            border-radius: 5px;
            box-shadow: 7px 6px 28px 1px rgba(0, 0, 0, 0.24);
            cursor: pointer;
            outline: none;
            transition: 0.2s all;
        }

        /* Adding transformation when the button is active */
        .btn:active {
            transform: scale(0.98);
            /* Scaling button to 0.98 to its original size */
            box-shadow: 3px 2px 22px 1px rgba(0, 0, 0, 0.24);
            /* Lowering the shadow */
        }
    </style>
</head>

<body>
    <button class="btn">Button</button>
</body>

</html>

Output

2. Using translate() Fnction

The translateY() function moves an element along the Y-axis by a specified amount. This movement can simulate the button being pressed downwards.

Syntax

transform: translateY()
html
<!DOCTYPE html>
<html>

<head>
    <style>
        .btn {
            padding: 15px 40px;
            font-size: 16px;
            text-align: center;
            cursor: pointer;
            outline: none;
            color: #fff;
            background-color: green;
            border: none;
            border-radius: 5px;
        }

        /* Adding styles on 'active' state */
        .btn:active {
            box-shadow: 7px 6px 28px 1px rgba(0, 0, 0, 0.24);
            transform: translateY(4px);
            /* Moving button 4px to y-axis */
        }
    </style>
</head>

<body>
    <button class="btn">Click Me</button>
</body>

</html>

Output

CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.



Similar Reads