Daily Tips & Tricks for Web Enthusiasts

HTML for Keyboard Shortcuts

If you’re writing technical instructions, documentation, or educational material that includes keyboard shortcuts, make sure you use the <kbd> element where appropriate.

Here’s what the HTML5 specification has this to say about the <kbd> element:

The <kbd> element represents user input (typically keyboard input, although it may also be used to represent other input, such as voice commands).

There are two things that make this element really great:

  1. It provides a clean, semantic way to define keyboard input.
  2. It makes it very easy to visually style keyboard input in a distinct way.

By default, text inside a <kbd> element is rendered with a monospace font, but it’s very easy to style this element to suit your own needs. Here on Core Assistance, for example, I often use the <kbd> element when I talk about keyboard shortcuts, so I wrote some CSS that makes <kbd> elements look like actual keyboard keys. Here’s an example: If you’re on a Mac, you can press Command + R to reload this page.

Here’s the CSS I use for <kbd> elements on Core Assistance. I’ve added some comments to explain what each declaration does. Feel free to use this CSS as-is on your own site or as a jumping-off point for your own <kbd> styles:

kbd {
    /* It all begins with a solid border. */
    border-style: solid;

    /* Make the border 1px thick on the top and both sides, but 3px thick on the bottom.  This gives these elements a nice raised appearance. */
    border-width: 1px 1px 3px;

    /* Round the corners a bit.  I'm using the em unit because I want the rounding of the corners to scale with the text. */
    border-radius: .25em;

    /* Use the same font-family as the surrounding text. */
    font-family: inherit;

    /* Give the text inside the borders a little breathing room. */
    padding: .1em .25em;

You may also need to adjust the line-height of your text so these styles don’t interfere with other text.