How to use the HTML href Attribute

The href Attribute

The 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 <a>:

<a href="link-path">Click</a>

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:

<a>Home</a>

Now to make the <a> element into a hyperlink, we add the href attribute:

<a href>Home</a>

And assign it a value of "/":

<a href="/">Home</a>

How it renders in the browser:

Home

For good measure, let’s break the anchor element example apart:

  • <a> is an opening anchor tag
  • </a>is a closing anchor tag
  • Home is content (the only part visible in the browser)
  • href is 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 <nav>...</nav>.

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 index.html
  • About should be about.html
  • Contact should be contact.html

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

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

Link to my YouTube channel (TechStacker).


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on