How to Create Anchor Link in HTML: Simple Guide
To create an anchor link in HTML, use the
<a> tag with the href attribute pointing to an ID or URL. For example, <a href="#section1">Go to Section 1</a> links to an element with id="section1" on the same page.Syntax
The anchor link uses the <a> tag with the href attribute. The href can be:
- A URL to link to another page.
- A hash
#followed by an element'sidto jump within the same page.
The target element must have a matching id attribute.
html
<a href="#target-id">Link text</a> <!-- Target element --> <div id="target-id">Content here</div>
Example
This example shows an anchor link that jumps to a section titled "Section 2" on the same page.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Anchor Link Example</title> </head> <body> <h1>Welcome</h1> <p><a href="#section2">Go to Section 2</a></p> <p>Some content here...</p> <p>More content...</p> <h2 id="section2">Section 2</h2> <p>This is the target section that the link jumps to.</p> </body> </html>
Output
A page with a link labeled 'Go to Section 2'. Clicking it scrolls the page down to the heading 'Section 2' and its paragraph.
Common Pitfalls
- For internal links, forgetting to add the
idattribute on the target element causes the link not to work. - Using spaces or special characters in
idvalues can break the link. - Using
href="#"without a proper target scrolls to the top of the page, which can confuse users.
html
<!-- Wrong: Missing target id --> <a href="#missing">Go to Missing</a> <!-- Right: Matching id on target --> <div id="missing">Target content</div>
Quick Reference
Use this quick guide to create anchor links:
| Part | Description | Example |
|---|---|---|
| <a> tag | Defines the clickable link | <a href="#section">Link</a> |
| href attribute | Specifies the link target | #section or URL |
| id attribute | Marks the target element | <h2 id="section">Title</h2> |
| # in href | Indicates internal page link | href="#section" |
Key Takeaways
The target element must have a matching id attribute.
Avoid spaces or special characters in id values.
Anchor links can also point to external URLs using href.
Test links to ensure they scroll or navigate correctly.