<a>: The Anchor element
Baseline Widely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
* Some parts of this feature may have varying levels of support.
The<a>HTML element (oranchor element), withitshref attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address.
Content within each<a>should indicate the link's destination. If thehref attribute is present, pressing the enter key while focused on the<a> element will activate it.
In this article
Try it
<p>You can reach Michael at:</p><ul> <li><a href="https://example.com">Website</a></li> <li><a href="mailto:m.bluth@example.com">Email</a></li> <li><a href="tel:+123456789">Phone</a></li></ul>li { margin-bottom: 0.5rem;}Attributes
This element's attributes include theglobal attributes.
attributionsrcDeprecatedSpecifies that you want the browser to send an
Attribution-Reporting-Eligibleheader. On the server-side this is used to trigger sending anAttribution-Reporting-Register-Sourceheader in the response, to register anavigation-based attribution source.The browser stores the source data associated with the navigation-based attribution source (as provided in the
Attribution-Reporting-Register-Sourceresponse header) when the user clicks the link. See theAttribution Reporting API for more details.There are two versions of this attribute that you can set:
Boolean, i.e., just the
attributionsrcname. This specifies that you want theAttribution-Reporting-Eligibleheader sent to the same server as thehrefattribute points to. This is fine when you are handling the attribution source registration on the same server.Value containing one or more URLs, for example:
htmlattributionsrc="https://a.example/register-sourcehttps://b.example/register-source"This is useful in cases where the requested resource is not on a server you control, or you just want to handle registering the attribution source on a different server. In this case, you can specify one or more URLs as the value of
attributionsrc. When the resource request occurs, theAttribution-Reporting-Eligibleheader will be sent to the URL(s) specified inattributionsrcin addition to the resource origin. These URLs can then respond with theAttribution-Reporting-Register-Sourceto complete registration.Note:Specifying multiple URLs means that multiple attribution sources can be registered on the same feature. You might for example have different campaigns that you are trying to measure the success of, which involve generating different reports on different data.
<a>elements cannot be used as attribution triggers, only sources.downloadCauses the browser to treat the linked URL as a download. Can be used with or without a
filenamevalue:Without a value, the browser will suggest a filename/extension, generated from various sources:
- The
Content-DispositionHTTP header - The final segment in the URLpath
- Themedia type (from the
Content-Typeheader, the start of adata:URL, orBlob.typefor ablob:URL)
- The
filename: defining a value suggests it as the filename./and\characters are converted to underscores (_). Filesystems may forbid other characters in filenames, so browsers will adjust the suggested name if necessary.
Note:
downloadonly works forsame-origin URLs, or theblob:anddata:schemes.- How browsers treat downloads varies by browser, user settings, and other factors. The user may be prompted before a download starts, or the file may be saved automatically, or it may open automatically, either in an external application or in the browser itself.
- If the
Content-Dispositionheader has different information from thedownloadattribute, resulting behavior may differ:- If the header specifies a
filename, it takes priority over a filename specified in thedownloadattribute. - If the header specifies a disposition of
inline, Chrome and Firefox prioritize the attribute and treat it as a download. Old Firefox versions (before 82) prioritize the header and will display the content inline.
- If the header specifies a
hrefThe URL that the hyperlink points to. Links are not restricted to HTTP-based URLs — they can use any URL scheme supported by browsers:
- Telephone numbers with
tel:URLs - Email addresses with
mailto:URLs - SMS text messages with
sms:URLs - Executable code with
#"/en-US/docs/Web/API/Navigator/registerProtocolHandler">registerProtocolHandler()
Moreover other URL features can locate specific parts of the resource, including:
- Sections of a page with document fragments
- Specific text portions withtext fragments
- Pieces of media files with media fragments
- Telephone numbers with
hreflangHints at the human language of the linked URL. No built-in functionality. Allowed values are the same asthe global
langattribute.interestforExperimentalNon-standardDefines the
<a>element as aninterest invoker. Its value is theidof the target element, which will be affected in some way (normally shown or hidden) when interest is shown or lost on the invoker element (for example, by hovering/unhovering or focusing/blurring it). SeeUsing interest invokers for more details and examples.pingA space-separated list of URLs. When the link is followed, the browser will send
POSTrequests with the bodyPINGto the URLs. Typically for tracking.referrerpolicyHow much of thereferrer to send when following the link.
no-referrer: TheRefererheader will not be sent.no-referrer-when-downgrade: TheRefererheader will not be sent toorigins withoutTLS (HTTPS).origin: The sent referrer will be limited to the origin of the referring page: itsscheme,host, andport.origin-when-cross-origin: The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path.same-origin: A referrer will be sent forsame origin, but cross-origin requests will contain no referrer information.strict-origin: Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP).strict-origin-when-cross-origin(default): Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP).unsafe-url: The referrer will include the originand the path (but not thefragment,password, orusername).This value is unsafe, because it leaks origins and paths from TLS-protected resources to insecure origins.
relThe relationship of the linked URL as space-separated link types.
targetWhere to display the linked URL, as the name for abrowsing context (a tab, window, or
<iframe>). The following keywords have special meanings for where to load the URL:_self: The current browsing context. (Default)_blank: Usually a new tab, but users can configure browsers to open a new window instead._parent: The parent browsing context of the current one. If no parent, behaves as_self._top: The topmost browsing context. To be specific, this means the "highest" context that's an ancestor of the current one. If no ancestors, behaves as_self._unfencedTop: Allows embeddedfenced frames to navigate the top-level frame (i.e., traversing beyond the root of the fenced frame, unlike other reserved destinations). Note that the navigation will still succeed if this is used outside of a fenced frame context, but it will not act like a reserved keyword.
Note:Setting
target="_blank"on<a>elements implicitly provides the samerelbehavior as settingrel="noopener"which does not setwindow.opener.typeHints at the linked URL's format with aMIME type. No built-in functionality.
Deprecated attributes
charsetDeprecatedHinted at thecharacter encoding of the linked URL.
Note:This attribute is deprecated andshould not be used by authors. Use the HTTP
Content-Typeheader on the linked URL.coordsDeprecatedUsed withthe
shapeattribute. A comma-separated list of coordinates.nameDeprecatedWas required to define a possible target location in a page. In HTML 4.01,
idandnamecould both be used on<a>, as long as they had identical values.Note:Use the global attribute
idinstead.revDeprecatedSpecified a reverse link; the opposite ofthe
relattribute. Deprecated for being very confusing.shapeDeprecatedThe shape of the hyperlink's region in an image map.
Note:Use the
<area>element for image maps instead.
Accessibility
>Strong link text
The content inside a link should indicate where the link goes, even out of context.
Inaccessible, weak link text
A sadly common mistake is to only link the words "click here" or "here":
<p>Learn more about our products <a href="/products">here</a>.</p>Result
Accessible, strong link text
Luckily, this is an easy fix, and it's actually shorter than the inaccessible version!
<p>Learn more <a href="/products">about our products</a>.</p>Result
Assistive software has shortcuts to list all links on a page. However, strong link text benefits all users — the "list all links" shortcut emulates how sighted users quickly scan pages.
onclick events
Anchor elements are often abused as fake buttons by setting theirhref to# or#"/en-US/docs/Web/HTML/Reference/Elements/button"> instead. In general,you should only use a hyperlink for navigation to a real URL.<button>
External links and linking to non-HTML resources
Links that open in a new tab/window viatarget="_blank", or links that point to a download file should indicate what will happen when the link is followed.
People experiencing low vision conditions, navigating with the aid of screen reading technology, or with cognitive concerns may be confused when a new tab, window, or application opens unexpectedly. Older screen-reading software may not even announce the behavior.
Link that opens a new tab/window
<a href="https://www.wikipedia.org"> Wikipedia (opens in new tab)</a>Result
Link to a non-HTML resource
If an icon is used to signify link behavior, make sure it has analt attribute to describe its purpose. In case the icon is missing, thealt attribute's content will still convey the link's behavior.
<p> <a href="https://www.wikipedia.org/"> Wikipedia <img src="new-tab.svg" width="14" alt="(Opens in new tab)" /> </a> <br /> <a href="2017-annual-report.ppt"> 2017 annual report <img src="powerpoint.svg" width="14" alt="(PowerPoint file)" /> </a></p><p> <a href="https://www.wikipedia.org/"> Wikipedia <img src="missing-icon.svg" width="14" alt="(Opens in new tab)" /> </a> <br /> <a href="2017-annual-report.ppt"> 2017 annual report <img src="missing-icon.svg" width="14" alt="(PowerPoint file)" /> </a></p>Result
Skip links
Askip link is a link placed as early as possible in<body> content that points to the beginning of the page's main content. Usually, CSS hides a skip link offscreen until focused.
<body> <a href="#content">Skip to main content</a> <header>…</header> <!-- The skip link jumps to here --> <main></main></body>.skip-link { position: absolute; top: -3em; background: white;}.skip-link:focus { top: 0;}Result
Skip links let keyboard users bypass content repeated throughout multiple pages, such as header navigation.
Skip links are especially useful for people who navigate with the aid of assistive technology such as switch control, voice command, or mouth sticks/head wands, where the act of moving through repetitive links can be laborious.
Size and proximity
Size
Interactive elements, like links, should provide an area large enough that it is easy to activate them. This helps a variety of people, including those with motor control issues and those using imprecise inputs such as a touchscreen. A minimum size of 44×44CSS pixels is recommended.
Text-only links in prose content are exempt from this requirement, but it's still a good idea to make sure enough text is hyperlinked to be easily activated.
- Understanding Success Criterion 2.5.5: Target Size
- Target Size and 2.5.5
- Quick test: Large touch targets
Proximity
Interactive elements, like links, placed in close visual proximity should have space separating them. Spacing helps people with motor control issues, who may otherwise accidentally activate the wrong interactive content.
Spacing may be created using CSS properties likemargin.
Examples
>Linking to an absolute URL
HTML
<a href="https://www.mozilla.com">Mozilla</a>Result
Linking to relative URLs
HTML
<a href="//example.com">Scheme-relative URL</a><a href="/en-US/docs/Web/HTML">Origin-relative URL</a><a href="p">Directory-relative URL</a><a href="./p">Directory-relative URL</a><a href="../p">Parent-directory-relative URL</a>a { display: block; margin-bottom: 0.5em;}Result
Linking to an element on the same page
<!-- <a> element links to the section below --><p><a href="#Section_further_down">Jump to the heading below</a></p><!-- Heading to link to --><h2>Section further down</h2>Result
Note:You can usehref="#top" or the empty fragment (href="#") to link to the top of the current page,as defined in the HTML specification.
Linking to an email address
To create links that open in the user's email program to let them send a new message, use themailto: scheme:
<a href="mailto:nowhere@mozilla.org">Send email to nowhere</a>Result
For details aboutmailto: URLs, such as including a subject or body, seeEmail links orRFC 6068.
Linking to telephone numbers
<a href="tel:+49.157.0156">+49 157 0156</a><a href="tel:+1(800)555-0123">(800) 555-0123</a>Result
tel: link behavior varies with device capabilities:
- Cellular devices autodial the number.
- Most operating systems have programs that can make calls, like Skype or FaceTime.
- Websites can make phone calls with
registerProtocolHandler, such asweb.skype.com. - Other behaviors include saving the number to contacts, or sending the number to another device.
SeeRFC 3966 for syntax, additional features, and other details about thetel: URL scheme.
Using the download attribute to save a <canvas> as a PNG
To save a<canvas> element's contents as an image, you can create a link where thehref is the canvas data as adata: URL created with JavaScript and thedownload attribute provides the file name for the downloaded PNG file:
Example painting app with save link
HTML
<p> Paint by holding down the mouse button and moving it. <a href="" download="my_painting.png">Download my painting</a></p><canvas width="300" height="300"></canvas>CSS
html { font-family: sans-serif;}canvas { background: white; border: 1px dashed;}a { display: inline-block; background: #6699cc; color: white; padding: 5px 10px;}JavaScript
const canvas = document.querySelector("canvas");const c = canvas.getContext("2d");c.fillStyle = "hotpink";let isDrawing;function draw(x, y) { if (isDrawing) { c.beginPath(); c.arc(x, y, 10, 0, Math.PI * 2); c.closePath(); c.fill(); }}canvas.addEventListener("mousemove", (event) => draw(event.offsetX, event.offsetY),);canvas.addEventListener("mousedown", () => (isDrawing = true));canvas.addEventListener("mouseup", () => (isDrawing = false));document .querySelector("a") .addEventListener( "click", (event) => (event.target.href = canvas.toDataURL()), );Result
Security and privacy
<a> elements can have consequences for users' security and privacy. SeeReferer header: privacy and security concerns for information.
Usingtarget="_blank" withoutrel="noreferrer" andrel="noopener" makes the website vulnerable towindow.opener API exploitation attacks, although note that, in newer browser versions settingtarget="_blank" implicitly provides the same protection as settingrel="noopener". Seebrowser compatibility for details.
Technical summary
| Content categories | Flow content,phrasing content,interactive content, palpable content. |
|---|---|
| Permitted content | Transparent, except that no descendant may beinteractive content or an<a> element, and no descendant may have a specifiedtabindex attribute. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that acceptsflow content, but not other<a> elements. |
| Implicit ARIA role | link whenhref attribute is present, otherwisegeneric |
| Permitted ARIA roles | When When
|
| DOM interface | HTMLAnchorElement |
Specifications
| Specification |
|---|
| HTML> # the-a-element> |
Browser compatibility
See also
<link>is similar to<a>, but for metadata hyperlinks that are invisible to users.:linkis a CSS pseudo-class that will match<a>elements with URL inhrefattribute that was not yet visited by the user.:visitedis a CSS pseudo-class that will match<a>elements with URL inhrefattribute that was visited by the user in the past.:any-linkis a CSS pseudo-class that will match<a>elements withhrefattribute.- Text fragments are user-agent instructions added to URLs that allow content authors to link to specific text on a page, without IDs being required.