Sub topic 2
Creating links with the a element
This chapter assumes you can write a basic HTML document (html, head, body), open it in a browser, and read file paths such as guides/setup.html. It also assumes you know that an element has a tag, attributes, and content.
The working model
The a (anchor) element makes a hyperlink. The href attribute holds the destination. The content between the tags is the link text, which the visitor clicks.
<a href="https://example.com/">Example site</a>The browser reads href, resolves it to a full URL, and navigates there when the visitor activates the link. Without href, the element is a placeholder and is not a link. It gets no link styling, is not focusable by keyboard, and does nothing when clicked.
Three kinds of href value
The value of href can take three forms. The next chapter covers how each one resolves, so here is just the overview.
<a href="https://example.com/">Example site</a>
<a href="/docs/intro.html">Introduction (root-relative)</a>
<a href="guides/setup.html">Setup guide (relative)</a>
<a href="../index.html">Back to the parent folder</a>- An absolute URL includes the scheme and host, and works from any page.
- A root-relative path starts with
/and is read from the top of the current site. - A relative path is read from the folder of the current page.
../means one folder up.
What a link can contain
Link text is the usual content, but the a element can wrap other inline content such as em or img. Keep the whole link inside one a element. Do not put one link inside another, because nested links are invalid and browsers handle them inconsistently.
Common errors
- Forgetting the scheme.
href="example.com"is a relative path to a file namedexample.com, not a website. Writehttps://example.com/. - Mistyped paths. A relative path that works on your computer can fail on the server if the folder or letter case differs. Many servers treat
Setup.htmlandsetup.htmlas different files. - Missing quotes or a missing closing tag. An unclosed
amakes the rest of the page part of the link. - Using
awithouthreffor a button. If the action does not navigate, use abuttonelement instead.
Practice
Exercise
A page contains <a href="example.com">Visit</a> and clicking it leads to a "not found" error on your own site. What is wrong, and how do you fix it?
Show answer
With no scheme, the browser treats example.com as a relative path to a file in the current folder. Add the scheme and write <a href="https://example.com/">Visit</a>.
Exercise
Why is <a>Contact us</a> not a working link, and what single change makes it one?
Show answer
It has no href attribute, so it has no destination and is not focusable or clickable as a link. Adding href, for example <a href="/contact.html">Contact us</a>, fixes it.