Styling button elements to look like links

Here’s a common scenario: you’re coding up a form with lots of buttons or need to add some elements that trigger JavaScript functions, and in the design comp some of these elements look like links. You intuitively reach for the a element, put some in the markup, add event handlers to them, and style them to match the design.

But wait a bit. Leaving the issue of putting elements that may rely on JavaScript to work in the markup for another time, should those elements really be links? What does the text on them say? What happens when you click them? If they trigger some kind of action that doesn’t match the normal link behaviour of going to another URL, it’s quite likely that you should really be using buttons.

Yes, I know. The designer says these elements need to look like links, period. And there was a time when making HTML buttons look like links wasn’t really possible in a cross-browser way. But these days you can get very, very close. It’s a bit tricky, but possible.

I’m focusing on the button element here. You may be able to achieve similar results with input[type="button"] elements.

Let’s take a look at the CSS:

.text {
    overflow:visible; /* Shrinkwrap the text in IE7- */
    margin:0;
    padding:0;
    border:0;
    color:#8f1f08; /* Match your link colour */
    background:transparent;
    font:inherit; /* Inherit font settings (doesn’t work in IE7-) */
    line-height:normal; /* Override line-height to avoid spacing issues */
    text-decoration:underline; /* Make it look linky */
    cursor:pointer; /* Buttons don’t make the cursor change in all browsers */
    -moz-user-select:text; /* Make button text selectable in Gecko */
}
/* Make sure keyboard users get visual feedback */
.text:hover,
.text:focus {
    color:#800000;
    background-color:#e3e0d1;
}
/* Remove mystery padding in Gecko browsers.
 * See https://bugzilla.mozilla.org/show_bug.cgi?id=140562
 */
.text::-moz-focus-inner {
    padding:0;
    border:0;
}

The comments should explain the non-obvious parts.

To see this in action, take a look at the Styling button elements to look like links demo page.

And a final note: just because you can make buttons look like links doesn’t necessarily mean you should. But this bit of CSS is useful when an element really should be a button, the design says it should look like a link, and changing the design is not an option.

Posted on October 4, 2011 in CSS

Comments are disabled for this post (read why), but if you have spotted an error or have additional info that you think should be in this post, feel free to contact me.