Search code examples
htmlbuttonhyperlinkanchor

How do I create an HTML button that acts like a link?


How do I create an HTML button that acts like a link? So that clicking the button redirects the user to a page.

I want it to be accessible, and with minimal extra characters or parameters in the URL.


Solution

  • HTML

    The plain HTML way is to put it in a <form> wherein you specify the desired target URL in the action attribute.

    <form action="https://google.com">
        <input type="submit" value="Go to Google" />
    </form>
    

    If necessary, set CSS display: inline; on the form to keep it in the flow with the surrounding text. Instead of <input type="submit"> in above example, you can also use <button type="submit">. The only difference is that the <button> element allows children.

    You'd intuitively expect to be able to use <button href="https://google.com"> analogous with the <a> element, but unfortunately no, this attribute does not exist according to HTML specification.

    CSS

    If CSS is allowed, simply use an <a> which you style to look like a button.

    <a href="https://google.com" class="button">Go to Google</a>
    
    a.button {
        padding: 1px 6px;
        border: 1px outset buttonborder;
        border-radius: 3px;
        color: buttontext;
        background-color: buttonface;
        text-decoration: none;
    }
    

    Or pick one of those many CSS libraries like Bootstrap.

    <a href="https://google.com" class="btn btn-primary">Go to Google</a>
    

    Noted should be that, historically, the CSS appearance:button property worked as well in some browsers, but this was experimental and ended up being considered a misfeature. Only none or auto are allowed on <a> elements.

    JavaScript

    If JavaScript is allowed, set the window.location.href.

    <input type="button" onclick="location.href='https://google.com';" value="Go to Google" />
    

    Instead of <input type="button"> in above example, you can also use <button>. The only difference is that the <button> element allows children.