How do I Create an HTML Button That Acts Like a Link?
If you have a button on your website that you want to act as a link, there are a few ways to achieve this.
By following these methods, you can either wrap the button in a link tag or style a link to look like a button using CSS.
Method 1: Wrapping the Button in a Link Tag#
One way to make a button act like a link is by wrapping the button in an <a> tag. Here is an example:
However, this approach is not recommended for accessibility reasons. If you validate this HTML using the W3C Markup Validation Service, you'll receive an error indicating that the button element should not be a descendant of the <a> element.
It can also cause confusion for keyboard users and may not behave as expected.
Additionally, if you choose to use a link as a button, you should override its role using the ARIA role attribute, like this:
<button role="link">
This ensures that screen readers will correctly identify the element as a link.
Method 2: Styling a Link to Look Like a Button#
Alternatively, you can style a link to resemble a button using CSS. Here is an example:
<a class="btn" href="https://example.com">Go to Example</a>
To apply styles, you can use a CSS class like btn in the above example. Here is a simple set of styles you can use:
.btn { text-decoration: none; padding: 0.5rem; border: 1px solid #333333; }
However, it's important to note that links and buttons serve different purposes. Links are primarily used to navigate users to a new location, while buttons are intended for triggering actions such as form submission or menu opening.
Method 3: Adding a Button Inside a Form#
If you want to incorporate a button that acts as a link within a form, you can set the form's action attribute to the desired link URL. Here is an example:
<form action="https://example.com"> <button type="submit">Go to Example</button> </form>
Alternatively, you can use the onclick attribute to change the location when the button is clicked:
<form> <button type="reset" onclick="location.href='https://example.com'"> Go to Example </button> </form>
Conclusion#
While it is possible to make a button act like a link or style a link to look like a button, it is generally recommended to avoid these practices.
Links and buttons have distinct purposes, and using them interchangeably can lead to usability and accessibility issues.
If you must choose between the two, consider styling a link to resemble a button, especially if it aligns with a specific design requirement.