(Progress persistence is disabled until Phase 9)
Links and Navigation
Learn how to connect pages together using hyperlinks.
Learning Objectives
- Learn how to create links using the anchor tag
- Understand the href attribute
- Understand the difference between absolute and relative URLs
- Learn how to open links in a new tab safely
The Anchor Tag
The ability to link documents together is what makes the World Wide Web a “web”!
To create a hyperlink in HTML, we use the anchor tag: <a>.
However, just having an <a> tag isn’t enough. The tag needs to know where to take the user when they click it. To tell the anchor tag where to go, we must provide an href (Hypertext Reference) attribute.
Syntax / Structure
<a href="URL">Clickable Text</a>
Code Example
<p>Visit the <a href="https://wikipedia.org">Wikipedia homepage</a> to learn more.</p>
Absolute vs Relative URLs
The href attribute can point to URLs in two different ways: absolute and relative.
Absolute URLs
An absolute URL contains the complete, full web address, including the protocol (https://) and the domain name. You use absolute URLs when you want to link to a completely different website.
<a href="https://google.com">Search on Google</a>
Relative URLs
A relative URL points to a file relative to the current page on the exact same website. You use relative URLs to link between pages on your own site.
Because the browser already knows you are on yourwebsite.com, you don’t need to type the full domain.
<!-- Links to yourwebsite.com/about -->
<a href="/about">About Us</a>
<!-- Links to yourwebsite.com/contact -->
<a href="/contact">Contact</a>
Opening Links in a New Tab
By default, clicking a link replaces the current page with the new page. Sometimes (especially when linking to a different website), you want the link to open in a new browser tab.
To do this, use the target="_blank" attribute.
Security Consideration
When you open external links in a new tab, you should always add the rel="noopener noreferrer" attribute. This prevents the new tab from maliciously gaining access to the window that opened it, protecting your users.
<a href="https://external-website.com" target="_blank" rel="noopener noreferrer">
Visit External Site
</a>
Try It Yourself
Try creating a link to your favorite website!
Key Takeaways
- Use the
<a>tag to create hyperlinks. - The
hrefattribute defines the destination URL. - Use Absolute URLs (
https://...) to link to external websites. - Use Relative URLs (
/about) to link to pages on your own website. - Use
target="_blank"withrel="noopener noreferrer"to safely open links in new tabs.