CodePark/ questions / Forms & inputs
START PRACTICINGPRACTICE
Frontend question · CSS & HTML › Forms & inputs

When should you use a button and when an a element?

Use a with an href for navigation: going to another page, a URL or a fragment (a part of the same page, like #comments). Use button for actions on the current page: submitting a form, opening a menu or toggling a setting.

Links behave like links:

  • Users can open them in a new tab, bookmark them and copy them.
  • They activate with Enter.
  • Screen readers announce them as links.

Buttons activate with both Enter and Space, and screen readers announce them as buttons.

Common mistakes:

  • a href="#" with a click handler. It has the wrong role, breaks middle-click and adds a fake history entry.
  • div onclick. It can't take focus, has no keyboard support and has no role.

Also remember that a button inside a form defaults to type="submit". Set type="button" for buttons that should not submit the form.

  • A link navigates, and a button performs an action.
  • They behave differently with the keyboard: Space activates only buttons.
  • Avoid href="#" links and div click handlers.
  • A button inside a form defaults to type="submit".