Add Hyperlinks – <a>
The <a>
tag, called the anchor tag, is used for adding hyperlinks. You can make hyperlinks to external websites or to other pages on the same website. We'll explain how to add hyperlinks in both situations in this lesson.
Key attributes
There are two frequently used attributes for the <a>
tag: href
and target
.
href
(hypertext reference): Used for setting the URL of an external website or a file path on the same website.target
: Used for setting how to open a linked document."_self"
: Open the linked document in the same frame. As this is the default value, if you don't specify anything, this option will automatically be chosen by the browser."_blank"
: Open the linked document in a new tab.
Add a hyperlink to an external website
To add a hyperlink to an external website, use the URL of the target website.
Example
<a href="https://www.google.com/"> Click Here!</a>
Add a hyperlink to another page on the same website
To add a hyperlink to another page on the same website, use the file path (relative path) of the target page.
Example
<a href="product.html"> Click Here!</a>
Open the page in a new tab
Add an attribute target="_blank"
to let users open the linked page in a new tab
rel="noopener noreferrer"
When you add a hyperlink to an external website, you may not know if the website is safe. This means that you need to be careful about cybersecurity issues. Your original page can be manipulated by JavaScript. To avoid the risk, it is better to add another attribute (rel="noopener noreferrer"
) to prevent the manipulation of the original page.
Note: rel
is an attribute of <a>
tag; rel
specifies the relationship between the current document and the linked document.
Example
<a href="https://www.google.com/" target="_blank" rel="noopener noreferrer">
Click Here!
</a>
Practice
Objective:
Add different types of hyperlinks to your web page
1. Add <a> elements the body section of the HTML file
Open chapter4.html with VS code and add three types of hyperlinks:
- To an external website: Google.com
- To each chapter document (under the project directory)
- To Google.com with an attribute of
target="_blank"
Add the code below in the chapter4.html file.
<h2>Hyperlinks</h2>
<a href="https://www.google.com/">To Google</a>
<br>
<a href="chapter2.html">Chapter 2. Preparing for Website Coding</a>
<br>
<a href="chapter3.html">Chapter 3. HTML Basics</a>
<br>
<a href="chapter4.html">Chapter 4. HTML: Add Links and Images</a>
<br>
<a href="https://www.google.com/" target="_blank" rel="noopener noreferrer">To Google with a new tab</a>
Note: <br>
is used to add a line break. As the <a>
tag is an inline element, text content is rendered in the same line without the <br>
tag.
3. Check the result with a browser
When opening the chapter4.html file with a browser, you can see a list of hyperlinks.