1.4 Working with Links and URLs
Links are an essential part of HTML, allowing users to navigate between web pages, sections of a page, or even external resources like images or documents. The HTML <a> (anchor) element defines a hyperlink.
Creating Links
To create a basic hyperlink, use the <a> tag with the href attribute, which specifies the URL to which the link points.
<a href="https://www.example.com">Visit Example.com</a>
The above example creates a hyperlink to "https://www.example.com". Clicking on the text "Visit Example.com" will take the user to that URL.
Linking to Other Pages
To link to another page on the same website, you can provide a relative URL in the href attribute.
<a href="about.html">About Us</a>
This example links to a page called "about.html" in the same directory.
Opening Links in a New Tab
If you want the link to open in a new browser tab, add the target="_blank" attribute to the <a> tag.
<a href="https://www.example.com" target="_blank">Open Example.com in a new tab</a>
Linking to an Email Address
To create a link that allows users to send an email, use the mailto: protocol in the href attribute.
<a href="mailto:someone@example.com">Send Email</a>
Linking to Specific Sections of a Page
You can link to a specific section of a web page using anchors. First, assign an id attribute to the target element, and then create a link to that id with the # symbol.
<h2 id="section1">Section 1</h2> <a href="#section1">Go to Section 1</a>
Clicking the link will scroll the page to the section with the corresponding id.
Linking to a Phone Number
To create a link that allows users to call a phone number directly from a mobile device, use the tel: protocol.
<a href="tel:+123456789">Call Us</a>
Absolute vs. Relative URLs
There are two types of URLs used in hyperlinks: absolute and relative.
- Absolute URLs: These contain the full path, including the protocol (http or https), domain name, and any path to the resource.
<a href="https://www.example.com/about.html">About Us</a>
<a href="about.html">About Us</a>
Link States
There are different states a link can be in, which can be styled using CSS:
- a:link – A normal, unvisited link.
- a:visited – A link the user has already visited.
- a:hover – A link when the user mouses over it.
- a:active – A link the moment it is clicked.
Example: Styling Link States
a:link { color: blue; } a:visited { color: purple; } a:hover { color: red; } a:active { color: green; }