Pushable” but­ton in pure CSS

Created: Wed Apr 10 17:10:23 CEST 2019

Last mod­i­fied: Wed Apr 10 21:27:13 CEST 2019


In this short tu­to­r­ial you will learn how to add a push-on-hover effect to your but­tons.

We are given a but­ton:

The HTML for such a but­ton is a sim­ple <a> link and the CSS looks like this:

text-decoration: none;
padding-left: 10px;
padding-right: 10px;
border-radius: 5px 5px;
background-color: green;
color: white;

Now how do we add the shadow? Simple:

box-shadow: -5px 5px 0px grey;

Animating on hover

Two steps; the first would be mov­ing the but­ton a few pix­els down­left.

Arbitrarily, let’s say we want our but­ton to be pushed down by two pixels.

a:hover {
    transform: translate(-2px,2px);
}

The sec­ond step is to re­duce the shad­ow’s size. So that it ap­pears to stay at the same po­si­tion.

Because our but­ton moved by two pix­els, our shadow will need to move” in the op­po­site di­rec­tion by the same amount of pix­els.

The math is sim­ple: 5 - 2 = 3

a:hover {
    box-shadow: -3px 3px 0px grey;
}

And it’s done.

Side notes

Doesn’t work on smart­phones and tablets. Also you might need to use vendor pre­fixes to en­sure full browser com­pat­i­bil­ity for the transform property.

source code