2635

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.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Andrew
  • 227,796
  • 193
  • 515
  • 708
  • 63
    Change GET to POST. Nobody seems to have addressed the OP's first problem, which was the `?` on the URL. This is caused by the form being `type="GET"`, change this to `type="POST"` and the `?` at the end of the URL disappears. This is because GET sends all variables in the URL, hence the `?`. – redfox05 Feb 18 '16 at 17:20
  • 15
    @redfox05 This works in a context where you are not strict about which method you accept for your pages. In a context where you reject posts on pages that are expecting `GET` it will fail. I still think that using a link make sense with the caveat that it will not react to "spacebar" when active like button does. Also some style and behavior will be different (such as draggable). If you want the true "button-link" experience, having server side redirects for URL finishing by `?` to remove it might be also an option. – Nicolas Bouvrette May 15 '16 at 15:49
  • 5
    http://www.cssbuttongenerator.com/ might come in handy if you want to create a button with css. – snow Sep 02 '16 at 00:29
  • 5
    I think it is better iade to create a link that looks like a button – yasar Jul 24 '18 at 13:56
  • 10
    Just a note, for me "button acts like link" means, that I can do right-click and decide whether to open in new tab/window, which is not working with JS solutions... – Betlista Dec 04 '18 at 10:33
  • 1
    Form submission works even when JavaScript is turned off. And forms can act like Bootstrap columns or other styling, if you add class or style attributes to the button element. Is the trailing ? still a problem in 2021? – David Spector Apr 17 '21 at 19:30
  • 4
    This is the [most copied question on SO](https://stackoverflow.blog/2021/04/19/how-often-do-people-actually-copy-and-paste-from-stack-overflow-now-we-know). – Varun Vejalla Apr 23 '21 at 04:58
  • 2
    @redfox05 Changing a GET to a POST just to not have a `?` on the URL is a terrible idea. GET means send me the information at this place, POST means something is being changed on the server. If you refresh a page after a POST, you get a warning. Caching is disabled. CDNs will behave differently. If you want something that "acts like a link", the correct solution is to use a link. You can then style the link or something inside it to look like a button. You could probably even put an actual – rjmunro Aug 12 '21 at 15:27
  • 1
    You might want to avoid using a button as a link, as some browsers treat them differently. You can style a `` to make it look like a button – mm4096 Oct 30 '21 at 04:21
  • 1
    There are a lot of [duplicate answers](https://stackoverflow.com/questions/2906582/how-to-create-an-html-button-that-acts-like-a-link?page=3&tab=oldest#comment124718423_70480943). – Peter Mortensen Jan 02 '22 at 01:49
  • 1
    For some reason, the cleanup of duplicate answers for [this question](https://stackoverflow.com/questions/2003505/) is much more efficient (100 answers of which 59 are deleted (41 left)). – Peter Mortensen Jan 02 '22 at 14:20

35 Answers35

2807

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 using among others the appearance property (it's only not supported in Internet Explorer).

<a href="https://google.com" class="button">Go to Google</a>
a.button {
    -webkit-appearance: button;
    -moz-appearance: button;
    appearance: button;

    text-decoration: none;
    color: initial;
}

Or pick one of those many CSS libraries like Bootstrap.

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

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 109
    Simple and nice. A fine solution. Add `display: inline` to the form to keep the button in the flow. – Pekka May 25 '10 at 16:44
  • 16
    in safari, this adds a question mark to the end of the url...is there a way to do it that doesn't add anything to the url? – Andrew May 25 '10 at 20:03
  • 2
    @Andrew that is probably because of the `GET` method used by default by the form everywhere but in IE. You could switch the form `method` to `POST` but that would have other consequences, namely when you use the history to browse back after clicking the button. It may be unavoidable (it will have no effect anyway). – Pekka May 25 '10 at 20:09
  • 14
    @BalusC Nice solution, but if it is inside some other form (parent form), then pressing this button redirects to address in the parent's form action attribute. – Vladimir Feb 04 '14 at 16:08
  • 4
    @Wlad: nesting forms is [illegal](http://validator.w3.org) in HTML anyway. Browser's behavior is unspecified and should not be relied upon. – BalusC Feb 04 '14 at 16:52
  • 1
    @Wlad if you'd like this functionality, using a form, "inside" the form, keeping it "legal", you could place it outside the parent form and position it using css – Sam Vloeberghs Mar 02 '14 at 16:14
  • 129
    Is it just me or is the –  Apr 29 '14 at 09:11
  • 4
    I like to add `style="cursor:pointer;"` to make act like a link also. – Sam Jul 19 '14 at 15:59
  • 4
    This will not work when the page your linking to already has get variables encoded in it (i.e. ```http://domain.com/search?query=test```). Compound that with the fact that it will add a question mark and I really feel this should not be chosen as the correct answer -- it encourages people to use a hack that will eventually fail in edge cases. – birchbark Dec 25 '14 at 16:33
  • 17
    Looks simple and nice, but may have side effects if not considered properly. i.e. creating 2nd form in page, nested form etc. – Tejasvi Hegde Jan 16 '15 at 13:56
  • 2
    @Tejasvi: "Side effects"? Those things are just basic HTML mistakes. The HTML developer would then better take a step back and restart learning basic HTML. – BalusC Jan 16 '15 at 13:59
  • 2
  • 3
    @gerdi: Why would the href attribute make sense on the button element, let alone obviously so? A button is not a hyperlink. That said, perhaps XHTML 2 will be of interest to you... – BoltClock Apr 24 '16 at 11:37
  • 2
    What if I want CTRL + Click to open the link in a new tab? This won't work with a button – Victor May 21 '16 at 10:42
  • I used that but in the end I had to copy all button attributes to this class so that the button looks exactly the same. Without it text of the button barely fit within the button borders. – Brambor Jan 02 '18 at 17:07
  • this would only mimic opening the link in the target window rather than target blank – Muhammad Omer Aslam Jan 26 '18 at 15:10
  • this seems to work: – sijones Dec 27 '18 at 05:24
  • Unfortunately the Company Outlook blocks the button unless you press additional step "View in Browser". Any ideas how to get around that? – compski Nov 28 '19 at 14:54
  • 1
    Why would you have a form submit approach just for navigation?? Ridiculous – Adam Hey Apr 20 '20 at 16:24
  • The problem is the "A that looks like a button" is that it doesn't automatically respond to the enter key, right? @AdamHey perhaps because the destination of the link is dynamic based on the content of the form? – Lucretiel Jul 26 '20 at 18:34
  • 1
    The problem with the HTML example is that when query params are added, form will not respect them and proceed without as technically they will have to be s within the
    .
    – Tim Daubenschütz Oct 22 '20 at 12:39
  • You should reconsider why and if you need a button in your design. If really necessary, you can style anchor elements to look like a button really quickly, no need for bootstrap. – MonkeyVoodoo Apr 27 '21 at 13:15
  • @MonkeyVoodoo: indeed. – BalusC Apr 27 '21 at 13:45
  • Accessibility speaking, which one do you think is better between **the form** and **the JS** one? – rlatief Jun 13 '22 at 11:38
  • the form only didn't work for me – Cris Oct 30 '22 at 18:24
  • You forgot that you can wrap a ` – Parking Master Feb 17 '23 at 21:44
  • Nope, I didn't forgot that ;) – BalusC Feb 18 '23 at 18:18
899

<button onclick="location.href='http://www.example.com'" type="button">
         www.example.com</button>

Note that the type="button" attribute is important, since its missing value default is the Submit Button state.

Boiethios
  • 38,438
  • 19
  • 134
  • 183
Adam
  • 43,763
  • 16
  • 104
  • 144
  • Insn't it `window.location.href='http://www.example.com'` ? location.href doesn't seem to work for me in IE9... – Benjamin Crouzier Dec 10 '12 at 14:15
  • 1
    @pinouchon Should work. window is implied. Could be an IE9 bug, http://stackoverflow.com/questions/7690645/ie9-window-location-href-error – Adam Dec 10 '12 at 17:56
  • 19
    It seems that if you don't specify type="button" this won't always work. Looks like the button will default to "submit" – kenitech Feb 03 '14 at 19:17
  • 101
    If you want to open the link in a new window/tab use: onclick="window.open('http://www.example.com','_blank');" – bennos Jun 16 '14 at 11:02
  • 6
    @kenitech [correct, according to specs](http://www.w3.org/TR/2011/WD-html5-20110525/the-button-element.html#the-button-element): "The *missing value default* is the **Submit Button** state." – Niels Keurentjes Jul 20 '14 at 13:26
  • 9
    but user cannot right click open in new tab, for that to work , u need the anchor tag – Irshu Nov 25 '14 at 16:35
  • @kenitech how to specify type="button"? I mean what object do you use? (input) ? –  Dec 08 '14 at 11:56
  • @RehanMehdi This was a long time ago. I guess I was saying – kenitech Dec 09 '14 at 18:51
  • 14
    Please don't do this. It breaks so many things such as the right-click context menu for links. – Navin May 05 '18 at 23:57
  • 1
    Note that the "location.href" part is simply JS. It resets the "window" object to have a new location with an href of whatever. Thus you could use other JS commands here as well, for instance, if you wanted to open the link in a new tab, you could use: ` – Damian Green Aug 09 '18 at 20:23
  • 2
    type=button does not seem to be relevant any more. – Timo Dec 08 '20 at 20:30
  • This is the key. Adding type="button" was the key for me. – viveknaskar Oct 20 '21 at 07:16
468

If it's the visual appearance of a button you're looking for in a basic HTML anchor tag then you can use the Twitter Bootstrap framework to format any of the following common HTML type links/buttons to appear as a button. Please note the visual differences between version 2, 3 or 4 of the framework:

<a class="btn" href="">Link</a>
<button class="btn" type="submit">Button</button>
<input class="btn" type="button" value="Input">
<input class="btn" type="submit" value="Submit">

Bootstrap (v4) sample appearance:

Sample output of Boostrap v4 buttons

Bootstrap (v3) sample appearance:

Sample output of Boostrap v3 buttons

Bootstrap (v2) sample appearance:

Sample output of Boostrap v2 buttons

Bern
  • 7,808
  • 5
  • 37
  • 47
  • 61
    Seems a little overkill for styling a single button, no? With border, padding, background, and other CSS effects you can style buttons and links to look similar without bringing over an entire framework. The methodology Bootstrap uses is good, however using Bootstrap seems excessive. – scottkellum May 12 '15 at 21:16
211

Use:

<a href="http://www.stackoverflow.com/">
    <button>Click me</button>
</a>

Unfortunately, this markup is no longer valid in HTML5 and will neither validate nor always work as potentially expected. Use another approach.

Hagyn
  • 922
  • 7
  • 14
D'Arcy Rittich
  • 167,292
  • 40
  • 290
  • 283
  • This markup seems valid at this point, according to the HTML spec: https://w3c.github.io/html-reference/a.html#a-changes – JCollier Mar 12 '23 at 07:15
170

As of HTML5, buttons support the formaction attribute. Best of all, no JavaScript or trickery is needed.

<form>
  <button formaction="http://stackoverflow.com">Go to Stack Overflow!</button>
</form>

Caveats

  • Must be surrounded by <form> tags.
  • The <button> type must be "submit" (or unspecified) - I couldn't get it working with type "button." Which brings up the point below.
  • Overrides the default action in a form. In other words, if you do this inside another form it's going to cause a conflict.

Reference: formaction

Browser Support: <button>: The Button element

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
EternalHour
  • 8,308
  • 6
  • 38
  • 57
  • 7
    Just to complete information: `formaction` is compatible since "_IE world_" since version **10** and above – Luca Detomi Oct 02 '15 at 08:44
  • @LucaDetomi - That is correct, however it is HTML5 specific. I've added another link with support data. – EternalHour Oct 02 '15 at 13:18
  • 2
    @EternalHour Genuinely curious. In the examples you and I have provided is there supposed to be an appreciable difference between the behavior of those two forms? In this specific case does ` – pseudosavant Oct 05 '15 at 00:57
  • 3
    @pseudosavant - The difference is that your answer relies on Javascript in order to work. In this solution, no Javascript is needed, it's straight HTML. – EternalHour Oct 05 '15 at 05:20
  • 3
    @EternalHour Sorry, I should have been more clear. Obviously the JS makes mine different but it is just a progressive enhancement. The form still goes to that link without the JS. I was curious about the intended behavior of just the HTML `
    `s in each of our examples. Is `formaction` on a `button` supposed to add the `?` to an empty GET submission? In this [JSBin](http://output.jsbin.com/rudicu) it looks like the HTML behaves exactly the same for both.
    – pseudosavant Oct 05 '15 at 19:15
  • If you want to open the uri in a new tab, you should add formtarget="_blank" to the button. – hbulens May 03 '17 at 02:55
  • 3
    Its useful to note that this only works when wrapped by form tags. Found that out the hard way... – Adsy2010 Jun 14 '17 at 21:23
  • @Adsy2010 - Yeah unfortunately, that's why I put them there. I did add some additional information to the answer that specifies that. – EternalHour Oct 30 '17 at 20:55
  • Just to let readers know: this DOES work in IE11, when using html5 and an enclosing form tag. – Katinka Hesselink Sep 20 '18 at 09:59
  • 1
    unfortunately, doesn't work when `formaction='#anchor'`. – Spongman Nov 12 '18 at 22:15
  • 1
    Interesting fact: You can have multiple buttons (and multiple urls) inside the form tags :) –  Jan 26 '19 at 00:56
  • This seemed really slick, but as someone mentioned it seems to add a `?` to the target URL upon navigation. I abandoned it and went back to `` links styled as buttons. – Garret Wilson Aug 08 '23 at 17:07
79

It is actualy very simple and without using any form elements. You can just use the <a> tag with a button inside :).

Like this:

<a href="http://www.google.com" target="_parent"><button>Click me !</button></a>

And it will load the href into the same page. Want a new page? Just use target="_blank".

EDIT

Couple of years later, while my solution still works, keep in mind you can use a lot of CSS to make it look whatever you want. This was just a fast way.

Lucian Minea
  • 1,300
  • 10
  • 12
42

If you are using an inside form, add the attribute type="reset" along with the button element. It will prevent the form action.

<button type="reset" onclick="location.href='http://www.example.com'">
    www.example.com
</button>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
saravanabawa
  • 1,607
  • 1
  • 16
  • 23
39
<form>
    <input type="button" value="Home Page" onclick="window.location.href='http://www.wherever.com'"> 
</form>
corn on the cob
  • 2,093
  • 3
  • 18
  • 29
ghoppe
  • 21,452
  • 3
  • 30
  • 21
  • 9
    @Robusto that was a snarky comment about the empty space that used to be there :) This is *not* a good solution IMO, as it won't work without JavaScript. – Pekka May 25 '10 at 16:47
  • 2
    @Pekka: yup, and also it's not even well-formed xhtml – Sean Patrick Floyd May 25 '10 at 16:49
  • 8
    if using form just use a submit, if using onclick why bother with the form. -1 – NimChimpsky Apr 26 '13 at 10:14
  • It is not well-formed HTML. The tag `input` does not have an ending tag. – Peter Mortensen Jul 21 '14 at 15:23
  • 13
    @PeterMortensen According to the [HTML spec](http://www.w3.org/TR/html-markup/input.button.html#input.button), the `input` element is a void element. It must have a start tag but must not have an end tag. – ghoppe Jul 21 '14 at 19:38
34

There seems to be three solutions to this problem (all with pros and cons).

Solution 1: Button in a form.

<form method="get" action="/page2">
    <button type="submit">Continue</button>
</form>

But the problem with this is that in some version of popular browsers such as Chrome, Safari and Internet Explorer, it adds a question mark character to the end of the URL. So in other words for the code above your URL will end up looking like this:

http://someserver/pages2?

There is one way to fix this, but it will require server-side configuration. One example using Apache Mod_rewrite would be to redirect all requests with a trailing ? to their corresponding URL without the ?. Here is an example using .htaccess, but there is a full thread here:

RewriteCond %{THE_REQUEST} \?\ HTTP [NC]
RewriteRule ^/?(index\.cfm)? /? [R=301,L]

Similar configurations can vary depending on the webserver and stack used. So a summary of this approach:

Pros:

  1. This is a real button, and semantically it makes sense.
  2. Since it is a real button, it will also act like a real button (e.g. draggable behavior and/or mimic a click when pressing space bar when active).
  3. No JavaScript, no complex style required.

Cons:

  1. Trailing ? looks ugly in some browsers. This can be fixed by a hack (in some cases) using POST instead of GET, but the clean way is to have a server-side redirect. The downside with the server side redirect is that it will cause an extra HTTP call for these links because of the 304 redirect.
  2. Adds extra <form> element
  3. Element positioning when using multiple forms can be tricky and becomes even worse when dealing with responsive designs. Some layout can become impossible to achieve with this solution depending on the order of the elements. This can end up impacting usability if the design is impacted by this challenge.

Solution 2: Using JavaScript.

You can use JavaScript to trigger onclick and other events to mimic the behavior of a link using a button. The example below could be improve and remove from the HTML, but it is there simply to illustrate the idea:

<button onclick="window.location.href='/page2'">Continue</button>

Pros:

  1. Simple (for basic requirement) and keep semantic while not requiring an extra form.
  2. Since it is a real button, it will also act like a real button (e.g. draggable behavior and/or mimic a click when pressing space bar when active).

Cons:

  1. Requires JavaScript which means less accessible. This is not ideal for a base (core) element such as a link.

Solution 3: Anchor (link) styled like a button.

Styling a link like a button is relatively easy and can provide similar experience across different browsers. Bootstrap does this, but it is also easy to achieve on your own using simple styles.

Pros:

  1. Simple (for basic requirement) and good cross-browser support.
  2. Does not need a <form> to work.
  3. Does not need JavaScript to work.

Cons:

  1. Semantic is sort of broken, because you want a button that acts like a link and not a link that acts like a button.
  2. It will not reproduce all behaviors of solution #1. It will not support the same behavior as button. For example, links react differently when dragged. Also the "space bar" link trigger will not work without some extra JavaScript code. It will add a lot of complexity since browsers are not consistent on how they support keypress events on buttons.

Conclusion

Solution #1 (Button in a form) seems like the most transparent for users with minimal work required. If your layout is not impacted by this choice and the server side tweak is feasible, this is a good option for cases where accessibility is the top priority (e.g. links on an error page or error messages).

If JavaScript is not an obstacle to your accessibility requirements, then solution #2 (JavaScript) would be preferred over #1 and #3.

If for some reason, accessibility is vital (JavaScript is not an option) but you are in a situation where your design and/or your server configuration is preventing you from using option #1, then solution #3 (Anchor styled like a button) is a good alternative solve this problem with minimal usability impact.

Community
  • 1
  • 1
Nicolas Bouvrette
  • 4,295
  • 1
  • 39
  • 53
34

You can simply put a tag around the element:

<a href="http://google.com" target="_blank">
    <button>My Button</button>
</a>

https://jsfiddle.net/hj6gob8b/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Uriahs Victor
  • 1,049
  • 14
  • 32
  • I'm not sure why this hasn't got more upvotes, to be honest. It works exactly as I need, and I did it this way because I wanted search engine spiders to be able to spot and follow the link. With JS that probably wouldn't have happened, and I'm not too sure of search engine behaviour when it comes to forms. It also doesn't result in any layout or behavioural side-effects (although I did assign a class to the anchor and set the `text-decoration` for that class to `none`). – Bart Read Jan 22 '17 at 12:53
  • 14
    No, you can't. HTML forbids nesting ` – Quentin Jan 22 '17 at 16:55
  • 8
    This is essentially the same as [this answer from years earlier](http://stackoverflow.com/a/21706048/19068). – Quentin Jan 22 '17 at 16:57
  • 6
    If it forbids it then why does it work? :) No serious developer takes heed to everything W3C validator says...try passing Facebook or Google or any huge website through there...The web isn't waiting for anyone – Uriahs Victor Jan 22 '17 at 20:43
  • 5
    @UriahsVictor It may work today, but one day browser vendors may decide to change the behavior as it isn't valid. – Jacob May 23 '17 at 21:42
  • @JacobAlvarez browser maintainers know better. This isn't something uncommon, they wouldn't want to go down as the browser which broke the internet. – Uriahs Victor May 24 '17 at 05:58
  • 5
    @UriahsVictor Flash and Java applets were pretty common too. – Jacob May 24 '17 at 15:04
  • 1
    The HTML spec does not forbid this now: https://w3c.github.io/html-reference/a.html#a-changes – JCollier Mar 12 '23 at 07:14
22

Just place your button inside of a reference tag, e.g.,

<a href="https://www.google.com/"><button>Next</button></a>

This seems to work perfectly for me and does not add any %20 tags to the link, just how you want it. I have used a link to Google to demonstrate.

You could of course wrap this in a form tag, but it is not necessary.

When linking another local file, just put it in the same folder and add the file name as the reference. Or specify the location of the file if in is not in the same folder.

<a href="myOtherFile"><button>Next</button></a>

This does not add any character onto the end of the URL either, however it does have the files project path as the URL before ending with the name of the file. e.g

If my project structure was...

.. denotes a folder \

  • denotes a file
    while four | denote a sub directory or file in parent folder

..public
|||| ..html
|||| |||| -main.html
|||| |||| -secondary.html

If I open file main.html, the URL would be,

http://localhost:0000/public/html/main.html?_ijt=i7ms4v9oa7blahblahblah

However, when I clicked the button inside main.html to change to secondary.html, the URL would be,

http://localhost:0000/public/html/secondary.html

No special characters are included at the end of the URL.

By the way - (%20 denotes a space in a URL it encoded and inserted in the place of them.)

Note: The localhost:0000 will obviously not be 0000. You'll have your own port number there.

Furthermore, the ?_ijt=xxxxxxxxxxxxxx at the end of the main.html URL, x is determined by your own connection, so obviously it will not be equal to mine.

It might seem like I'm stating some really basic points, but I just want to explain as best as I can.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
C.Gadd
  • 402
  • 3
  • 11
22

Seven ways to do that:

  1. Using window.location.href = 'URL'
  2. Using window.location.replace('URL')
  3. Using window.location = 'URL'
  4. Using window.open('URL')
  5. Using window.location.assign('URL')
  6. Using HTML form
  7. Using HTML anchor tag

<!-- Using window.location.href = 'URL' -->
<button onclick='window.location.href = "https://stackoverflow.com"'>
  Click Me
</button>

<!-- Using window.location.replace('URL') -->
<button onclick='window.location.replace("https://stackoverflow.com")'>
  Click Me
</button>

<!-- Using window.location = 'URL' -->
<button onclick='window.location = "https://stackoverflow.com"'>
  Click Me
</button>

<!-- Using window.open('URL') -->
<button onclick='window.open("https://stackoverflow.com","_self","","")'>
  Click Me
</button>

<!-- Using window.location.assign('URL') -->
<button onclick='window.location.assign("http://www.stackoverflow.com")'>
  Click Me
</button>

<!-- Using HTML form -->
<form action='https://stackoverflow.com' method='get'>
  <input type='submit' value='Click Me'/>
</form>

<!-- Using HTML anchor tag -->
<a href='https://stackoverflow.com'>
  <button>Click Me</button>
</a>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Adnan Toky
  • 1,756
  • 2
  • 11
  • 19
  • Right answer! Simple 1-liner that works. Just use 1 of the onclick= options. HTML anchor tag isn't valid, suggest taking it out. – can.do Apr 26 '22 at 15:15
21

If you want to avoid having to use a form or an input and you're looking for a button-looking link, you can create good-looking button links with a div wrapper, an anchor and an h1 tag. You'd potentially want this so you can freely place the link-button around your page. This is especially useful for horizontally centering buttons and having vertically-centered text inside of them. Here's how:

Your button will be comprised of three nested pieces: a div wrapper, an anchor, and an h1, like so:

.link-button-wrapper {
    width: 200px;
    height: 40px;
    box-shadow: inset 0px 1px 0px 0px #ffffff;
    border-radius: 4px;
    background-color: #097BC0;
    box-shadow: 0px 2px 4px gray;
    display: block;
    border:1px solid #094BC0;
}
.link-button-wrapper > a {
    display: inline-table;
    cursor: pointer;
    text-decoration: none;
    height: 100%;
    width:100%;
}
.link-button-wrapper > a > h1 {
    margin: 0 auto;
    display: table-cell;
    vertical-align: middle;
    color: #f7f8f8;
    font-size: 18px;
    font-family: cabinregular;
    text-align: center;
}
<div class="link-button-wrapper">
    <a href="your/link/here">
        <h1>Button!</h1>
    </a>
</div>

Here's a jsFiddle to check it out and play around with it.

Benefits of this setup: 1. Making the div wrapper display: block makes it easy to center (using margin: 0 auto) and position (while an <a> is inline and harder to positionand not possible to center).

  1. You could just make the <a> display:block, move it around, and style it as a button, but then vertically aligning text inside of it becomes hard.

  2. This allows you to make the <a> display: inline-table and the <h1> display: table-cell, which allows you to use vertical-align: middle on the <h1> and center it vertically (which is always nice on a button). Yes, you could use padding, but if you want your button to dynamically resize, that won't be as clean.

  3. Sometimes when you embed an <a> within a div, only the text is clickable, this setup makes the whole button clickable.

  4. You don't have to deal with forms if you're just trying to move to another page. Forms are meant for inputting information, and they should be reserved for that.

  5. Allows you to cleanly separte the button styling and text styling from each other (stretch advantage? Sure, but CSS can get nasty-looking so it's nice to decompose it).

It definitely made my life easier styling a mobile website for variable-sized screens.

TylerH
  • 20,799
  • 66
  • 75
  • 101
MoMo
  • 499
  • 3
  • 12
20

Going along with what a few others have added, you can go wild with just using a simple CSS class with no PHP, no jQuery code, just simple HTML and CSS.

Create a CSS class and add it to your anchor. The code is below.

.button-link {
    height:60px;
    padding: 10px 15px;
    background: #4479BA;
    color: #FFF;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    border: solid 1px #20538D;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4);
    -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);
}
.button-link:hover {
    background: #356094;
    border: solid 1px #2A4E77;
    text-decoration: none;
}
<HTML>
    <a class="button-link" href="http://www.go-some-where.com"
       target="_blank">Press Here to Go</a>

That is it. It is very easy to do and lets you be as creative as you'd like. You control the colors, the size, the shapes(radius), etc. For more details, see the site I found this on.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
artie
  • 239
  • 3
  • 6
19

The only way to do this (except for BalusC's ingenious form idea!) is by adding a JavaScript onclick event to the button, which is not good for accessibility.

Have you considered styling a normal link like a button? You can't achieve OS specific buttons that way, but it's still the best way IMO.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • I think he is talking about not only functionality (click) but also appearance. –  May 25 '10 at 16:44
  • 1
    @Web Logic yup, that's why I'm talking about styling the link to look like a button. – Pekka May 25 '10 at 16:46
  • 6
    @ChrisMarisic there's many downsides to using onClick: it doesn't work with JS turned off; the user can't open a link in a new tab/window, nor copy the link into their clipboard for sharing; parsers and bots won't be able to recognize and follow the link; browsers with a "prefetch" feature won't recognize the link; and many more. – Pekka Aug 06 '14 at 15:06
  • 2
    While those are valid points, I don't really think that really address accessibility. Did you mean usability, not accessibility? In web development accessibility is usually reserved to be specifically about whether users who have visual impairments can operate your application well. – Chris Marisic Aug 06 '14 at 15:50
17

To Nicolas' answer, the following worked for me as that answer didn't have type="button" due to which it started behaving as submit type...since I already have one submit type. It didn't work for me ... and now you can either add a class to the button or to <a> to get the required layout:

<a href="http://www.google.com/">
    <button type="button">Click here</button>
</a>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bhawna Jain
  • 709
  • 10
  • 27
16

Another option is to create a link in the button:

<button type="button"><a href="yourlink.com">Link link</a></button>

Then use CSS to style the link and button, so that the link takes up the entire space within the button (so there's no miss-clicking by the user):

button, button a{position:relative;}
button a{top:0;left:0;bottom:0;right:0;}

I have created a demo here.

Keep in mind the spec says this is not valid as buttons should not contain any interactive descendants.

lukeocom
  • 3,243
  • 3
  • 18
  • 30
  • 11
    Keep in mind the spec says this is not valid as buttons should not contain any interactive descendants. http://www.w3.org/TR/2011/WD-html5-20110525/the-button-element.html – lukeocom Jan 20 '14 at 05:05
  • 2
    Both of you are correct. VS2015 flags this with a warning: "Element 'a' cannot be nested inside element 'button'" but it works with: IE11, Edge, Chrome, Firefox, Safari and at least some (perhaps all) mobile browsers currently. So don't use this technique but if you did in the past, it works for now ;) – Zeek2 Jun 27 '17 at 08:02
  • 1
    Can you address the alleged [failure to pass HTML validation](https://stackoverflow.com/questions/2906582/how-to-create-an-html-button-that-acts-like-a-link/67614923#comment121310578_67614923) in your answer? Please respond by [changing your answer](https://stackoverflow.com/posts/21153367/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Jan 02 '22 at 01:58
11

If you want to create a button that is used for a URL anywhere, create a button class for an anchor.

a.button {
    background-color: #999999;
    color: #FFFFFF !important;
    cursor: pointer;
    display: inline-block;
    font-weight: bold;
    padding: 5px 8px;
    text-align: center;
    -webkit-border-radius: 5px;
    border-radius: 5px;
}
.button:hover {
    text-decoration: none;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Maarek
  • 682
  • 6
  • 6
9

I knew there have been a lot of answers submitted, but none of them seemed to really nail the problem. Here is my take at a solution:

  1. Use the <form method="get"> method that the OP is starting with. This works really well, but it sometimes appends a ? to the URL. The ? is the main problem.
  2. This solution works without JavaScript enabled. The fallback will add a ? to the end of the URL though.
  3. If JavaScript is enabled then you can use jQuery/JavaScript to handle following the link, so that ? doesn't end up appended to the URL. It will seamlessly fallback to the <form> method for the very small fraction of users who don't have JavaScript enabled.
  4. The JavaScript code uses event delegation so you can attach an event listener before the <form> or <button> even exist. I'm using jQuery in this example, because it is quick and easy, but it can be done in 'vanilla' JavaScript as well.
  5. The JavaScript code prevents the default action from happening and then follows the link given in the <form> action attribute.

JSBin Example (code snippet can't follow links)

// Listen for any clicks on an element in the document with the `link` class
$(document).on('click', '.link', function(e) {
    // Prevent the default action (e.g. submit the form)
    e.preventDefault();

    // Get the URL specified in the form
    var url = e.target.parentElement.action;
    window.location = url;
});
<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
        <meta charset="utf-8">
        <title>Form buttons as links</title>
    </head>
    <body>
        <!-- Set `action` to the URL you want the button to go to -->
        <form method="get" action="http://stackoverflow.com/questions/2906582/how-to-create-an-html-button-that-acts-like-a-link">
            <!-- Add the class `link` to the button for the event listener -->
            <button type="submit" class="link" role="link">Link</button>
        </form>
    </body>
</html>
pseudosavant
  • 7,056
  • 2
  • 36
  • 41
5

Create a button using the <a> tag and add proper CSS content:

.abutton {
  background: #bada55; padding: 5px; border-radius: 5px;
  transition: 1s; text-decoration: none; color: black;
}
.abutton:hover { background: #2a2;  }
<a href="https://example.com" class="abutton">Continue</a>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
4

People who have answered using <a></a> attributes on a <button></button> was helpful.

But then recently, I encountered a problem when I used a link inside a <form></form>.

The button is now regarded like/as a submit button (HTML5). I've tried working a way around and have found this method.

Create a CSS style button like the one below:

.btn-style {
    border: solid 1px #0088cc;
    border-radius: 6px;
    moz-border-radius: 6px;
    -webkit-box-shadow: 0px 0px 2px rgba(0, 0, 0, 1.0);
    -moz-box-shadow: 0px 0px 2px rgba(0, 0, 0, 1.0);
    box-shadow: 0px 0px 2px rgba(0, 0, 0, 1.0);
    font-size: 18px;
    color: #696869;
    padding: 1px 17px;
    background: #eeeeee;
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #eeeeee), color-stop(49%, #eeeeee), color-stop(72%, #cccccc), color-stop(100%, #eeeeee));
    background: -moz-linear-gradient(top, #eeeeee 0%, #eeeeee 49%, #cccccc 72%, #eeeeee 100%);
    background: -webkit-linear-gradient(top, #eeeeee 0%, #eeeeee 49%, #cccccc 72%, #eeeeee 100%);
    background: -o-linear-gradient(top, #eeeeee 0%, #eeeeee 49%, #cccccc 72%, #eeeeee 100%);
    background: -ms-linear-gradient(top, #eeeeee 0%, #eeeeee 49%, #cccccc 72%, #eeeeee 100%);
    background: linear-gradient(top, #eeeeee 0%, #eeeeee 49%, #cccccc 72%, #eeeeee 100%);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#eeeeee', endColorstr='#eeeeee', GradientType=0);
}

Or create a new one here: CSS Button Generator

And then create your link with a class tag named after the CSS style you have made:

<a href='link.php' class='btn-style'>Link</a>

Here's a fiddle:

JSFiddle

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Logan Wayne
  • 6,001
  • 16
  • 31
  • 49
4

Also you can use a button:

For example, in ASP.NET Core syntax:

// Some other tags
 <form method="post">
      <input asp-for="YourModelPropertyOrYourMethodInputName"
      value="@TheValue" type="hidden" />
      <button type="submit" class="link-button" formaction="/TheDestinationController/TheDestinationActionMethod">
      @(TextValue)
      </button>
  </form>
// Other tags...


<style>
       .link-button {
        background: none !important;
        border: none;
        padding: 0 !important;
        color: #20a8d8;
        cursor: pointer;
    }
</style>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Elnaz
  • 2,854
  • 3
  • 29
  • 41
3

For HTML 5 and a styled button along with an image background

<a id="Navigate" href="http://www.google.com">
  <input
    type="button"
    id="NavigateButton"
    style="
      background-image: url(http://cdn3.blogsdna.com/wp-content/uploads/2010/03/Windows-Phone-7-Series-Icons-Pack.png);
      background-repeat: no-repeat;
      background-position: -272px -112px;
      cursor:pointer;
      height: 40px;
      width: 40px;
      border-radius: 26px;
      border-style: solid;
      border-color: #000;
      border-width: 3px;" title="Navigate"
    />
</a>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anees Hameed
  • 5,916
  • 1
  • 39
  • 43
  • 5
    Doesn't validate. Pasting into https://validator.w3.org/nu/#textarea gives *Error: The element input must not appear as a descendant of the a element.* – Mark Amery Oct 04 '15 at 14:28
3

I used this for a website I'm currently working on and it worked great! If you want some cool styling too, I'll put the CSS down here.

input[type="submit"] {
  background-color: white;
  width: 200px;
  border: 3px solid #c9c9c9;
  font-size: 24pt;
  margin: 5px;
  color: #969696;
}

input[type="submit"]:hover {
  color: white;
  background-color: #969696;
  transition: color 0.2s 0.05s ease;
  transition: background-color 0.2s 0.05s ease;
  cursor: pointer;
}
<input type="submit" name="submit" onClick="window.location= 'http://example.com'">

A working JSFiddle is here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jasch1
  • 525
  • 2
  • 8
  • 22
3

You could also set the buttons type-property to "button" (it makes it not submit the form), and then nest it inside a link (makes it redirect the user).

This way you could have another button in the same form that does submit the form, in case that's needed. I also think this is preferable in most cases over setting the form method and action to be a link (unless it's a search-form I guess...)

Example:

<form method="POST" action="/SomePath">
  <input type="text" name="somefield" />
  <a href="www.target.com"><button type="button">Go to Target!</button></a>
  <button type="submit">submit form</button>
</form>

This way the first button redirects the user, while the second submits the form.

Be careful to make sure the button doesn't trigger any action, as that will result in a conflict. Also as Arius pointed out, you should be aware that, for the above reason, this isn't strictly speaking considered valid HTML, according to the standard. It does however work as expected in Firefox and Chrome, but I haven't yet tested it for Internet Explorer.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anders Martini
  • 828
  • 1
  • 14
  • 31
3

You can use JavaScript:

<html>
<button onclick='window.location = "http://www.google.com"'>
            Google
        </button>

</html>

Replace http://www.google.com with your website, and make sure to include http:// before the URL.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hayz
  • 176
  • 4
2

In JavaScript

setLocation(base: string) {
  window.location.href = base;
}

In HTML

<button onclick="setLocation('/<whatever>')>GO</button>"
2

Type window.location and press Enter in your browser console. Then you can get the clear idea what location contains:

   hash: ""
   host: "stackoverflow.com"
   hostname: "stackoverflow.com"
   href: "https://stackoverflow.com/questions/2906582/how-to-create-an-html-button- 
   that-acts-like-a-link"
   origin: "https://stackoverflow.com"
   pathname: "/questions/2906582/how-to-create-an-html-button-that-acts-like-a-link"
   port: ""
   protocol: "https:"

You can set any value from here.

So for redirecting another page, you can set the href value with your link.

   window.location.href = your link

In your case:

   <button onclick="window.location.href='www.google.com'">Google</button>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nasir Khan
  • 753
  • 1
  • 9
  • 22
2

HTML Answer: If you want to create an HTML button that acts like a link, use the two common attributes for it: <a> and/or action="":

<form action="stackoverflow.com"/>
   <button type="submit" value="Submit Form"

Or...

"href" is part of the <a> attribute. It helps direct links:

<a href="stackoverflow.com">Href</a>

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
gamer214
  • 23
  • 7
2

The Bootstrap approach also works with Bulma.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.2/css/bulma.min.css">
<a href="https://www.stackoverflow.com" class="button is-primary">Stack Overflow</a>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
2

none of the solutions here worked for me, so after trying all of them out I ended up with something trivial: HTML only (no form submit), no CSS, no JS:

<a href="/link"><button>Link</button></a>
Cris
  • 2,824
  • 24
  • 23
1

If you are using an SSL certificate:

<a href="https://www.google.com" target="_blank"><button>Click me !</button></a>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vikash Chauhan
  • 792
  • 2
  • 9
  • 18
0

If you're using a CSS library or a theme, just apply the classes of a button to the anchor/link tag.

Below is an example with One UI:

<a class="btn-block-option" href="">
    <i class="si si-reload"></i>
</a>
xxx
  • 1,153
  • 1
  • 11
  • 23
Sosu Alfred
  • 446
  • 3
  • 8
-3

If what you need is that it will look like a button, with emphasis on the gradient image, you can do this:

<a href="www.yourlink.com" class="btn btn-gradient"><i class="fa fa-home"> Button Text</i></a>
ilans
  • 2,537
  • 1
  • 28
  • 29
-3

If you want to create a button that acts as a link, there are multiple ways you can do this. Choose the one best for your situation. The code below creates a link inside a button.

<button>
  <a href="www.google.com">Go to Google</a>
</button>

The second way is to open a new window when the button is clicked

<button onclick="open('www.google.com')">Google</button>

Or maybe add event listeners

document.querySelector("#btn").addEventListener('click', open('www.google.com'))
<button id="btn">Go to Google</button>

There are many ways you can do this, but this is only three small examples of buttons that act like a link. In other words, buttons that open up links.