Links
Links connect pages to each other — they are what turns separate documents into the World Wide Web. A link is also called a hyperlink, hence "HyperText" in the name HTML.
A link
The <a> tag (from anchor) turns text into a link. Where it leads is set in the href attribute:
<a href="https://example.com">Go to example.com</a>The browser coloured the link blue and underlined it. Visited links turn purple.
Absolute addresses
An absolute address contains everything, starting with the https:// protocol. It leads to a specific page on the internet and works from anywhere:
<p><a href="https://example.com/docs/start">Documentation</a></p>
<p><a href="https://developer.mozilla.org">The MDN reference</a></p>Such addresses are used for links to other sites.
Relative addresses
A relative address is counted from the current page — you use it to link to pages of your own site. Suppose the files are laid out like this:
my-site/
├── index.html
├── about.html
└── blog/
└── first-post.html| From | Address in href | Where it leads |
|---|---|---|
index.html | about.html | A file in the same folder |
index.html | blog/first-post.html | A file in a subfolder |
blog/first-post.html | ../index.html | One folder up: .. is the parent folder |
| any page | /about.html | From the site root |
Jumping within a page
The id attribute gives an element a unique name. A link with a hash sign and that name scrolls the page to the element:
<p><a href="#prices">To prices</a></p>
<p style="height: 300px;">A long story about the coffee shop...</p>
<h2 id="prices">Prices</h2>
<p>Cappuccino — $4.</p>Click the link in the preview — the window scrolls to the Prices heading. This is how tables of contents in long articles work.
A new tab
The target="_blank" attribute opens the link in a new tab:
<a href="https://example.com" target="_blank">Opens in a new tab</a>Do not overuse it: the user decides where to open a link. A new tab makes sense, for example, for a document needed next to a form being filled in.
Email and phone
A link can do more than open a page. A mailto: address opens the mail app, and tel: offers to make a call on a phone:
<p><a href="mailto:hello@example.com">Write to us</a></p>
<p><a href="tel:+12025550123">+1 202 555 0123</a></p>Common mistake
Link text like "here" or "click here" says nothing about where the link leads. People using screen readers often listen to a list of all links on a page — and hear ten identical "here"s. Make the words that describe the target the link:
<p>Bad: the price list can be downloaded <a href="/price.pdf">here</a>.</p>
<p>Good: download the <a href="/price.pdf">price list as a PDF</a>.</p>