Pressed Button State With CSS

NOTE: I’ve covered button link styling using CSS3 in a more recent post which you can read here. The following post is an older method using images.


There is certain anchor state in CSS that I don’t see used very often – actually, it’s something I haven’t really used myself, but something which I now realize can be very useful. I’m talking about the “active” anchor state.

The active anchor state is the state an anchor (a link) is in when you click on it. The moment you click on a link, it becomes active. We all use the “hover” or “visited” states, but the active state can come in very handy when you’ve got custom styled buttons.

You see, on the desktop, whether on Windows, Linux or OS X, the buttons respond to you when you click on them. They visibly become pressed down, telling you that you’ve pushed them. This provides satisfying feedback to the user and makes the application feel more responsive.

On the web, such feedback is seldom given. You click on a button and nothing happens. In some browsers you’ll see a selection outline around the link or button while the next page is loading. Even buttons that have custom background images making them look like big solid buttons don’t do anything when you push them. They remain static and unresponsive.

It doesn’t have to be this way. Just use the “active” state to give your buttons a “pressed” look or whatever other look you wish. This will make your application or website stand out above the rest, as the experience will be closer to what the user is familiar to on the desktop rather than on the web. 

Ok, enough chit chat, here’s what you do:

Say you have a button in your application that uses a custom image. The markup would look something like this:

<a id="button"></a>

It’s an empty anchor with an id. We can use this id to style the anchor. Our CSS would then look like this:

#button {
  display: block;
  width: 135px;
  height: 43px;
  background: url(button.png) no-repeat top;
}

We’re simply turning the inline anchor into a block, giving it a width and a height, and setting a background image. The button will look like this:

To add the active state simply append “:active” after the anchor selector:

#button:active {
  background: url(button.png) no-repeat bottom;
}

Because my image contains both anchor states, we simply shift the background position to the bottom, which changes the look of the button to this: 

Here’s the image I’m talking about, and here’s a live demo.

Let me know what you think. I would definitely like to see more active states used on the web. With just a couple of lines of CSS you can make your site or app feel more responsive.

[Update 16 Dec 2008] William has posted a useful link in the comments to enable the “:active” class in IE. Here’s the fix.