Movatterモバイル変換


[0]ホーム

URL:


  1. Tecnologia Web para desenvolvedores
  2. HTML: Linguagem de Marcação de Hipertexto
  3. Referência HTML
  4. Elementos HTML
  5. <a>

Esta página foi traduzida do inglês pela comunidade.Saiba mais e junte-se à comunidade MDN Web Docs.

View in EnglishAlways switch to English

<a>

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨julho de 2015⁩.

* Some parts of this feature may have varying levels of support.

Oelemento<a> emHTML (ou elemento âncora), com o atributohref cria-se um hiperligação nas páginas web, arquivos, endereços de emails, ligações na mesma página ou endereços na URL. O conteúdo dentro de cada<a>precisará indicar o destino do link.

Experimente

<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;}

Atributos

Os atributos do elemento incluem osatributos globais.

download

Leva o usuário a salvar a URL em vez de navegar até ela. Pode ser usado com ou sem um valor:

  • Sem um valor, obrowser irá sugerir um nome de arquivo/extensão, gerado a partir de diversas origens:

  • A definição de um valor o sugere como o nome do arquivo. Caracteres/ e\ são convertidos paraunderscores (_).Arquivos de sistema talvez proibam alguns caracteres em nomes de arquivos, então o navegador irá ajustar o nome sugerido caso necessário.

Note:Notes:-download somente funciona paraURLs de mesma origem, ou os esquemasblob: edata:

  • SeContent-Disposition tiver um diferentefilename (nome do arquivo) quedownload, o cabeçalho tem prioridade. (SeContent-Disposition: inline, Firefox prioriza o cabeçalho enquanto o Chrome escolhedownload.)
href

A URL para a qual o hiperlink aponta. Links não se restrigem a URLs baseadas no protocolo HTTP — eles podem utilizar qualquer tipo de URL suportado pelos browsers:

  • Sections of a page with fragment URLs(Seções de página com fragmentos URL)
  • Pieces of media files with media fragments (Pedaços de arquivos de mídia com fragmentos da própria mídia)
  • Números de telefone comtel: URLs
  • Email addresses with(Endereço de email com)mailto: URLs
  • Alguns navegadores talvez não aguentem certos arranjos em URL, para isso os websites fazem uso doregisterProtocolHandler()
hreflang

Hints at the human language of the linked URL. No built-in functionality. Allowed values are the same asthe globallang attribute.

ping

Uma lista de URLs separadas por espaços. Quando o link é seguido, o brrowser enviará requisiçõesPOST com o corpoPING para as URLs. Typically for tracking.

referrerpolicyExperimental

Quanto doreferrer para ser enviado quando acessar o link. AcesseReferrer-Policy para possíveis valores e seus efeitos.

rel

The relationship of the linked URL as space-separatedlink types.

target

Where 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: No atual contexto de pesquisa. (Default)
  • _blank: Normalmente uma nova aba, porém usuários podem configurar seus navegadores para abrir em uma nova janela.
  • _parent: the parent browsing context of the current one. If no parent, behaves as_self.
  • _top: the topmost browsing context (the "highest" context that's an ancestor of the current one). If no ancestors, behaves as_self.

Nota:Quando usandotarget, adicionerel="noreferrer noopener" para evitar "exploit" parawindow.opener API;

Warning:Note: Linking to another page withtarget="_blank" will run the new page in the same process as your page. If the new page executes JavaScript, your page's performance may suffer. This can also be avoided by usingrel="noreferrer noopener".

type

Hints at the linked URL's format with aMIME type. No built-in functionality.

Obsolete attributes

charset

Hinted at thecharacter encoding of the linked URL.

Nota:This attribute is obsolete andshould not be used by authors. Use the HTTPContent-Type header on the linked URL.

coords

Used withtheshape attribute. A comma-separated list of coordinates.

name

Was required to define a possible target location in a page. In HTML 4.01,id andname could both be used on<a>, as long as they had identical values.

Nota:Use the global attributeid instead.

rev

Specified a reverse link; the opposite oftherel attribute. Deprecated for being very confusing.

shape

The shape of the hyperlink's region in an image map.

Nota:Use the<area> element for image maps instead.

Properties

Content categoriesFlow content,phrasing content,interactive content, palpable content.
Permitted contentTransparent, containing eitherflow content (excludinginteractive content) orphrasing content.
Tag omissionNenhuma, tanto a tag inicial quanto a final são obrigatórias.
Permitted parents Any element that acceptsphrasing content, or any element that acceptsflow content, but not other<a> elements.
Implicit ARIA rolelink whenhref attribute is present, otherwiseno corresponding role
Permitted ARIA roles

Whenhref attribute is present:

Whenhref attribute is not present:

  • any
DOM interfaceHTMLAnchorElement

Examples

Linking to an absolute URL

HTML

html
<a href="https://www.mozilla.com"> Mozilla </a>

Result

Linking to relative URLs

HTML

html
<a href="//example.com">Scheme-relative URL</a><a href="/pt-BR/docs/Web/HTML">Origin-relative URL</a><a href="./p">Directory-relative URL</a>
a {  display: block;  margin-bottom: 0.5em;}

Result

Linking to an element on the same page

html
<!-- <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>

Nota: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:

html
<a href="mailto:nowhere@mozilla.org">Send email to nowhere</a>

For details aboutmailto: URLs, such as including a subject or body, seeEmail links orRFC 6068.

Linking to telephone numbers

html
<a href="tel:+49.157.0156">+49 157 0156</a><a href="tel:+1(555)5309">(555) 5309</a>

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 withregisterProtocolHandler, 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 with adownload attribute and the canvas data as adata: URL:

Example painting app with save link

HTML
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
css
html {  font-family: sans-serif;}canvas {  background: #fff;  border: 1px dashed;}a {  display: inline-block;  background: #69c;  color: #fff;  padding: 5px 10px;}
JavaScript
js
var canvas = document.querySelector("canvas"),  c = canvas.getContext("2d");c.fillStyle = "hotpink";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 (vulnerability description).

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":

html
<p>Learn more about our products <a href="/products">here</a>.</p>

Strong link text

Luckily, this is an easy fix, and it's actually shorter than the inaccessible version!

html
<p>Learn more <a href="/products">about our products</a>.</p>

Assistive software have 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#"/pt-BR/docs/Web/HTML/Reference/Elements/button"><button> instead. In general,you should only use a hyperlink for navigation to a real URL.

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

html
<a href="https://www.wikipedia.org">  Wikipedia (opens in new tab)</a>

Link to a non-HTML resource

html
<a href="2017-annual-report.ppt"> 2017 Annual Report (PowerPoint) </a>

If an icon is used to signify link behavior, make sure it hasalt text:

html
<a href="https://www.wikipedia.org">  Wikipedia  <img alt="(opens in new tab)" src="newtab.svg" /></a><a href="2017-annual-report.ppt">  2017 Annual Report  <img alt="(PowerPoint file)" src="ppt-icon.svg" /></a>

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>  <main> <!-- The skip link jumps to here -->
css
.skip-link {  position: absolute;  top: -3em;  background: #fff;}.skip-link:focus {  top: 0;}

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.

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.

Specifications

Specification
HTML
# the-a-element

Compatibilidade com navegadores

See also

  • <link> is similar to<a>, but for metadata hyperlinks that are invisible to users.
  • :link is a CSS pseudo-class that will match<a> elements with validhref attributes.

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp