href attribute is one of the most important attributes in HTML.
href is used for specifying URLs for:
- Hyperlinks (also just called “links”).
- Or for importing external resources, such as styles and scripts.
The most common use case for
href is to add internal or external links (URLs) on the anchor element
Let’s create a link that takes the user to the front page when you click on it.
We’ll call it Home.
First, we define the anchor element:
Now to make the
<a> element into a hyperlink, we add the
And assign it a value of
How it renders in the browser:
For good measure, let’s break the anchor element example apart:
<a>is an opening anchor tag
</a>is a closing anchor tag
Homeis content (the only part visible in the browser)
hrefis an attribute name
=is an assignment operator
"/"is an attribute value
On this website, this exact anchor element is wrapping the TechStacker logo in the header’s top left corner (if you click on it, you’re taken to the front page).
You’ll often see this exact code example used inside websites’ navigation bar
Let’s say your website has a total of 3 pages, e.g. Home, About, Contact, and you want to make internal links for them.
First, each page’s HTML document should be named as such:
- Home should be
- About should be
- Contact should be
And then you define relative page routes (URLs) for each document as such:
<a href="/">Home</a> <a href="/about">About</a> <a href="/contact">Contact</a>
Now you can wrap each anchor element inside a
<nav> <a href="/">Home</a> <a href="/about">About</a> <a href="/contact">Contact</a> </nav>
Now you have a navigation component that you can put in the header, footer, or sidebar on your website.
If you want to link to another website than your own, you use an external link format, where you specify an absolute path:
<a href="https://www.youtube.com">Link to YouTube.com</a>
I’ll use this opportunity to link to my own YouTube channel: