How to create an HTML button that acts like a link
Solution 1
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.button {
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
text-decoration: none;
color: initial;
}
<a href="https://google.com" class="button">Go to Google</a>
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.
Solution 2
<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.
Solution 3
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:
Bootstrap (v3) sample appearance:
Bootstrap (v2) sample appearance:
Solution 4
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.
Solution 5
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
Mike
Updated on August 12, 2022Comments
-
Mike almost 2 years
I would like to create an HTML button that acts like a link. So, when you click the button, it redirects to a page. I would like it to be as accessible as possible.
I would also like it so there aren't any extra characters, or parameters in the URL.
How can I achieve this?
Based on the answers posted so far, I am currently doing this:
<form method="get" action="/page2"> <button type="submit">Continue</button> </form>
but the problem with this is that in Safari and Internet Explorer, it adds a question mark character to the end of the URL. I need to find a solution that doesn't add any characters to the end of the URL.
There are two other solutions to do this: Using JavaScript or styling a link to look like a button.
Using JavaScript:
<button onclick="window.location.href='/page2'">Continue</button>
But this obviously requires JavaScript, and for that reason it is less accessible to screen readers. The point of a link is to go to another page. So trying to make a button act like a link is the wrong solution. My suggestion is that you should use a link and style it to look like a button.
<a href="/link/to/page2">Continue</a>
-
redfox05 about 8 yearsChange 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 beingtype="GET"
, change this totype="POST"
and the?
at the end of the URL disappears. This is because GET sends all variables in the URL, hence the?
. -
Nicolas Bouvrette about 8 years@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. -
snow over 7 yearscssbuttongenerator.com might come in handy if you want to create a button with css.
-
yasar almost 6 yearsI think it is better iade to create a link that looks like a button
-
Betlista over 5 yearsJust 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...
-
David Spector about 3 yearsForm 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?
-
Varun Vejalla about 3 yearsThis is the most copied question on SO.
-
rjmunro almost 3 years@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 <button> into the <a> tag. -
mm4096 over 2 yearsYou might want to avoid using a button as a link, as some browsers treat them differently. You can style a
<a>
to make it look like a button -
Peter Mortensen over 2 yearsThere are a lot of duplicate answers.
-
Peter Mortensen over 2 yearsFor some reason, the cleanup of duplicate answers for this question is much more efficient (100 answers of which 59 are deleted (41 left)).
-
-
Admin almost 14 yearsI think he is talking about not only functionality (click) but also appearance.
-
Pekka almost 14 yearsSimple and nice. A fine solution. Add
display: inline
to the form to keep the button in the flow. -
Pekka almost 14 years@Web Logic yup, that's why I'm talking about styling the link to look like a button.
-
Pekka almost 14 years@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.
-
Sean Patrick Floyd almost 14 years@Pekka: yup, and also it's not even well-formed xhtml
-
Mike almost 14 yearsin 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?
-
Pekka almost 14 years@Andrew that is probably because of the
GET
method used by default by the form everywhere but in IE. You could switch the formmethod
toPOST
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). -
Benjamin Crouzier over 11 yearsInsn't it
window.location.href='http://www.example.com'
? location.href doesn't seem to work for me in IE9... -
Adam over 11 years@pinouchon Should work. window is implied. Could be an IE9 bug, stackoverflow.com/questions/7690645/…
-
NimChimpsky about 11 yearsif using form just use a submit, if using onclick why bother with the form. -1
-
lukeocom over 10 yearsKeep in mind the spec says this is not valid as buttons should not contain any interactive descendants. w3.org/TR/2011/WD-html5-20110525/the-button-element.html
-
kenitech over 10 yearsIt seems that if you don't specify type="button" this won't always work. Looks like the button will default to "submit"
-
Vladimir over 10 years@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.
-
BalusC over 10 years@Wlad: nesting forms is illegal in HTML anyway. Browser's behavior is unspecified and should not be relied upon.
-
Sam Vloeberghs about 10 years@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
-
Admin about 10 yearsIs it just me or is the <button> tag missing an obvious href attribute?
-
bennos almost 10 yearsIf you want to open the link in a new window/tab use: onclick="window.open('example.com','_blank');"
-
Sam almost 10 yearsI like to add
style="cursor:pointer;"
to make act like a link also. -
Niels Keurentjes almost 10 years@kenitech correct, according to specs: "The missing value default is the Submit Button state."
-
Peter Mortensen almost 10 yearsIt is not well-formed HTML. The tag
input
does not have an ending tag. -
ghoppe almost 10 years@PeterMortensen According to the HTML spec, the
input
element is a void element. It must have a start tag but must not have an end tag. -
Pekka almost 10 years@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.
-
Chris Marisic almost 10 yearsWhile 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.
-
Blake A. Nichols almost 10 yearsSet the button type="button", that will allow you to click it without submitting the form.
-
Irshu over 9 yearsbut user cannot right click open in new tab, for that to work , u need the anchor tag
-
Admin over 9 years@kenitech how to specify type="button"? I mean what object do you use? (input) ?
-
kenitech over 9 years@RehanMehdi This was a long time ago. I guess I was saying <input type="button" or something.
-
Arius over 9 yearsElement 'button' cannot be nested within element 'a'.
-
Anders Martini over 9 yearsaccording to the standard no, But in my experience this works fine though. Haven't cross-browser tested it extensively yet, but at least FF and Chrome seem to handle it just fine, with expected behaviour.
-
Anders Martini over 9 yearsArius: Read up a bit, experimented some more, and found that a button element can in fact be nested inside a <a> element, as long as the button element does not have its own action applied (since that would obviously result in a conflict - which action will the browser perform? the buttons or the <a>'s ?) but as long as you make sure the button-element itself doesn't trigger any action once clicked,this should work just fine (probably shouldn't be considered a best practice though)
-
Arius over 9 yearsIt's not about possibility. This is just against HTML5 specification and that's all.
-
birchbark over 9 yearsThis 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. -
Tejasvi Hegde over 9 yearsLooks simple and nice, but may have side effects if not considered properly. i.e. creating 2nd form in page, nested form etc.
-
BalusC over 9 years@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.
-
Henry over 9 yearsThis is not really a great solution semantically.
<a href="">
is the correct way to create a link. Plus you might run into some difficulty if your site is https and you're using this method to link to a non https page. -
Hyder B. about 9 yearsWhile this works, it should not be considered as a solution but a workaround because if you pass this code through W3C validator, you will get errors.
-
scottkellum about 9 yearsSeems 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.
-
Luca Detomi over 8 yearsJust to complete information:
formaction
is compatible since "IE world" since version 10 and above -
EternalHour over 8 years@LucaDetomi - That is correct, however it is HTML5 specific. I've added another link with support data.
-
Mark Amery over 8 yearsDoesn't validate. Pasting into validator.w3.org/nu/#textarea gives Error: The element input must not appear as a descendant of the a element.
-
pseudosavant over 8 years@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
<button formaction>
===<form action>
? -
EternalHour over 8 years@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.
-
pseudosavant over 8 years@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
<form>
s in each of our examples. Isformaction
on abutton
supposed to add the?
to an empty GET submission? In this JSBin it looks like the HTML behaves exactly the same for both. -
BoltClock about 8 years@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...
-
Soren about 8 yearsYou actually get a reasonable button without any CSS at all
-
Victor almost 8 yearsWhat if I want CTRL + Click to open the link in a new tab? This won't work with a button
-
Kiran Kotla over 7 yearsI'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 tonone
). -
Quentin over 7 yearsNo, you can't. HTML forbids nesting
<button>
inside<a>
. -
Quentin over 7 yearsThis is essentially the same as this answer from years earlier.
-
Uriahs Victor over 7 yearsIf 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
-
hbulens about 7 yearsIf you want to open the uri in a new tab, you should add formtarget="_blank" to the button.
-
Jacob almost 7 years@UriahsVictor It may work today, but one day browser vendors may decide to change the behavior as it isn't valid.
-
Uriahs Victor almost 7 years@JacobAlvarez browser maintainers know better. This isn't something uncommon, they wouldn't want to go down as the browser which broke the internet.
-
Jacob almost 7 years@UriahsVictor Flash and Java applets were pretty common too.
-
Adsy2010 almost 7 yearsIts useful to note that this only works when wrapped by form tags. Found that out the hard way...
-
Lucian Minea almost 7 yearsYes, Hyder B. you're right, but one you also should keep in mind that the standards are only raw guides. As a programmer you should always think outside the box and try things that are not in the book ;) .
-
Zeek2 almost 7 yearsFYI HTML also forbids the opposite (according to VS2015): nesting <a> inside <button> but that also works on: IE11, Edge, Firefox, Chrome and Safari and some/all mobile browsers.
-
Zeek2 almost 7 yearsBoth 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 ;)
-
EternalHour over 6 years@Adsy2010 - Yeah unfortunately, that's why I put them there. I did add some additional information to the answer that specifies that.
-
Brambor over 6 yearsI 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.
-
Muhammad Omer Aslam over 6 yearsthis would only mimic opening the link in the target window rather than target blank
-
Navin about 6 yearsPlease don't do this. It breaks so many things such as the right-click context menu for links.
-
Damian Green almost 6 yearsNote 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:
<button type="button" onclick="window.open('https://....', '_blank');">
. -
Katinka Hesselink over 5 yearsJust to let readers know: this DOES work in IE11, when using html5 and an enclosing form tag.
-
Spongman over 5 yearsunfortunately, doesn't work when
formaction='#anchor'
. -
sijones over 5 yearsthis seems to work:<a href="w3schools.com"> <button> Button </button> </a>
-
Admin over 5 yearsInteresting fact: You can have multiple buttons (and multiple urls) inside the form tags :)
-
Roko C. Buljan over 4 yearsNEVER wrap other anchors or form-action elements into Anchor.
-
Lucian Minea over 4 yearsAha, and why is that ?
-
compski over 4 yearsUnfortunately the Company Outlook blocks the button unless you press additional step "View in Browser". Any ideas how to get around that?
-
Stephen R over 4 yearsYou should use
<button type="button">...
so that it doesn't by default function as a Submit -
Stephen R over 4 yearsOnly if you want it to reset your form. Use
type="button"
-
Adam Hey about 4 yearsWhy would you have a form submit approach just for navigation?? Ridiculous
-
corn on the cob almost 4 yearsYou'll need some kind of https:// or http:// before the URL though. You can also link to local files using file:///
-
Lucretiel almost 4 yearsThe 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?
-
Tim Daubenschütz over 3 yearsThe 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 <input>s within the <form>.
-
Timo over 3 yearstype=button does not seem to be relevant any more.
-
MonkeyVoodoo about 3 yearsYou 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.
-
BalusC about 3 years@MonkeyVoodoo: indeed.
-
Peter Mortensen about 3 yearsDoes this work with current (2021) browsers?
-
Peter Mortensen about 3 yearsWhy is it different using an SSL certificate?
-
Peter Mortensen about 3 yearsAn explanation would be in order.
-
Peter Mortensen about 3 yearsHow is this different from previous answers (not a rhetorical question)?
-
Anders Martini almost 3 years@PeterMortense I haven't got a clue to be honest, I'm not doing much frontend work these days. shouldn't be too hard to find out though, just make a html document and try! :)
-
jdh8 almost 3 yearsThe button outside of the text does not link.
-
isherwood almost 3 yearsThis is invalid HTML.
-
isherwood almost 3 yearsI'm not sure what needs to be explained. This is the right element for navigation, and styling is at the developer's discretion.
-
Someone_who_likes_SE almost 3 yearsbutton element should NEVER be inside a elements.
-
General Grievance over 2 yearsPlease do not add duplicate answers. This answer has already covered using anchor in button: stackoverflow.com/questions/2906582/….
-
viveknaskar over 2 yearsThis is the key. Adding type="button" was the key for me.
-
Someone_who_likes_SE over 2 yearsThe validation says a link should never be inside a button.
-
Peter Mortensen over 2 yearsThis looks deceptively simple after 11 years and 63 answers (incl. deleted answers). I think extraordinary simple solutions require extraordinary explanations. Why would this work? Under what conditions (considering it apparently does not pass HTML validation)? The question included "page2" in the link. How does this match the question? Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
-
Peter Mortensen over 2 yearsThis is a duplicate of at least two answers, Sense of Science's answer and neevjs's answer (they may themselves both be duplicate answers).
-
Peter Mortensen over 2 yearsThe oldest answer this is a duplicate of is lukeocom's answer.
-
Peter Mortensen over 2 yearsThis is a duplicate of lukeocom's answer.
-
Peter Mortensen over 2 yearsThis is a duplicate of lukeocom's answer.
-
Peter Mortensen over 2 yearsCan you address the alleged failure to pass HTML validation in your answer? Please respond by changing your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
-
baash05 over 2 yearsthe only issue with this is inline JS is considered bad form and sometimes violates CSP's
-
thedebuggger over 2 yearsthank you so much for this simple answer.
-
brennanyoung over 2 yearsThere's a very good reason this is not valid code: Accessibility. Tab stops (e.g. links) should not contain tab stops (e.g. buttons) because Assistive Tech (screen readers etc.) do not know how to present them to the user. Ask yourself: Which one gets keyboard focus via tabbing? Which one is supposed to handle the click event? So, besides failing the HTML validator, you'll also violate WCAG, which can have legal consequences - a box which it is wiser not to think too far outside of.
-
can.do about 2 yearsRight answer! Simple 1-liner that works. Just use 1 of the onclick= options. HTML anchor tag isn't valid, suggest taking it out.
-
rlatief almost 2 yearsAccessibility speaking, which one do you think is better between the form and the JS one?
-
user229044 almost 2 yearsThis assumes both Bootstrap and FontAwesome, neither of which are mentioned in the question.