Skip to content

Instantly share code, notes, and snippets.

@cchaos
Last active February 27, 2020 20:57
Show Gist options
  • Save cchaos/f7e36e615aa650eff0baf56528b65ed3 to your computer and use it in GitHub Desktop.
Save cchaos/f7e36e615aa650eff0baf56528b65ed3 to your computer and use it in GitHub Desktop.
Button & Link best practices pulled from https://css-tricks.com/a-complete-guide-to-links-and-buttons/

Images/Icons inside buttons

<button>
   <svg aria-hidden="true" focusable="false">
     <path d="..." />
   </svg>
   <span class="callout">Big</span>
   Sale!
</button>

<button type="button">
  <span role="img" aria-label="Fox">
    🦊
  </span>
  Button
</button>

States

You may also want to use ARIA attributes for styling, which is a neat way to encourage using them correctly: https://css-tricks.com/user-facing-state/

button[aria-pressed="true"] { }
button[aria-pressed="false"] { }

"Once" handlers

Attach a click handler to a button that only runs once. To make that clear to the user, disable the button on click as well.

document.querySelector("button").addEventListener('click', function(event) {
  event.currentTarget.setAttribute("disabled", true);
}, {
    once: true
});

Then you would intentionally un-disable the button and reattach the handler when necessary.

Focus

Removing focus styles from clicks and not keyboard events has limited, but increasing, browser support

:focus:not(:focus-visible) { 
  outline: 0; 
}

Aria

  • aria-pressed: Turns a button into a toggle, between aria-pressed="true" and aria-pressed="false". More on button toggles, which can also be done with role="switch" and aria-checked="true".
  • aria-expanded: If the button controls the open/closed state of another element (like a dropdown menu), you apply this attribute to indicate that like aria-expanded="true".

Focus management

Focus management isn't just for dialogs. If clicking a button runs a calculation and changes a value on the page, there is no context change there, meaning focus should remain on the button. If the button does something like "move to next page," the focus should be moved to the start of that next page.

Size

The classic Apple guideline for the minimum size for a touch target (button) is 44x44pt.

a {
/* Grab color from nearest parent that sets it */
color: inherit;
/* Wipe out style (turn black) */
color: initial;
/* Change back to User Agent style (blue) */
color: revert;
}
/* Or */
.special-area a {
all: unset;
all: revert;
}

https://css-tricks.com/user-facing-state/

Active Navigation Links

http://tink.uk/using-the-aria-current-attribute/

<a href="#/features" aria-current="page">Features</a>

Active Buttons

More info on toggle buttons: https://inclusive-components.design/toggle-button/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment