HTML Links
HTML links, also known as Hyperlinks, are the cornerstone of web pages. Links allow users to navigate from one page to another, connecting the entire World Wide Web.
HTML uses the <a> tag (a is short for anchor) to create links.
<a href="url">Link Text</a>hrefAttribute: This is the most important attribute, specifying the target address (URL) of the link.- Link Text: This is the part visible to users on the page and can be clicked.
Example:
<a href="https://www.google.com">Visit Google</a>The above code produces the following effect: Visit Google
The target Attribute
The target attribute specifies where to open the linked document. It has several common values:
_self: Default. Opens the link in the current browser window or tab.html<a href="page.html" target="_self">Open in current window</a>_blank: Opens the link in a new browser window or tab. This is commonly used for external links to prevent users from leaving your site.html<a href="https://www.google.com" target="_blank">Open in new window</a>_parent: Opens the link in the parent frame (mainly used with<iframe>frame layouts)._top: Opens the link in the full browser window, breaking out of all frames.
Absolute URL vs. Relative URL
The address used in the href attribute can be absolute or relative.
Absolute URL: A complete web address pointing to another website.
html<a href="https://developer.mozilla.org/">MDN Web Docs</a>Relative URL: Points to a file within the current website. It doesn't include the domain name.
- Link to a file in the same directory:html
<a href="about.html">About Us</a> - Link to a file in a subdirectory:html
<a href="/products/product1.html">Product 1</a> - Link to a file in a parent directory:html
<a href="../index.html">Back to Home</a>
- Link to a file in the same directory:
Best Practice: Always use relative URLs within your website. This way, even if your domain name changes, internal links will still work.
Using an Image as a Link
You can place an <img> inside an <a> tag to create a clickable image link.
<a href="default.asp">
<img src="smiley.gif" alt="HTML Tutorial" style="width:42px;height:42px;">
</a>Linking to a Specific Part of a Page (Bookmarks)
You can create links that jump directly to a specific section of the current page or another page. This requires two steps:
Create the target anchor: Use the
idattribute to create a unique identifier for the element you want to jump to.html<h2 id="section2">Chapter 2</h2>Create the link to the anchor: In the
hrefattribute, use#followed by the target'sid.- Jump to an anchor on the current page:html
<a href="#section2">Jump to Chapter 2</a> - Jump to an anchor on another page:html
<a href="page2.html#section2">Jump to Chapter 2 on Page 2</a>
- Jump to an anchor on the current page:
mailto Links
You can create a special link that, when clicked, opens the user's default email client with the recipient address pre-filled.
<a href="mailto:someone@example.com">Send Email</a>