How to Link to Sections in HTML using id and #anchor
On long web pages, you may want users to jump directly to a specific section instead of scrolling manually.
This is done using the id
attribute with #anchor
links.
It’s a common technique used in:
Table of Contents
Documentation sites
Blogs with long articles
Add an id to a Section
The id
attribute gives a unique name to an HTML element.
Example:
<h2 id="about">About Us</h2>
<p>We are a leading academy teaching web development...</p>
Here, the heading <h2>
has an id named “about”
Create a Link to That Section
To link to the section, use #id-name
in the href
attribute.
Example:
<a href="#about">Go to About Us Section</a>
When clicked, the browser scrolls to the section with id="about"
.
Full Example: Linking Within a Page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Linking to Sections Example</title>
</head>
<body>
<h1>Website Navigation Example</h1>
<p><a href="#about">Go to About</a> | <a href="#contact">Go to Contact</a></p>
<h2 id="about">About Us</h2>
<p>We provide tutorials on HTML, CSS, and JavaScript.</p>
<h2 id="contact">Contact Us</h2>
<p>You can reach us at contact@example.com</p>
</body>
</html>
Linking to Sections on Another Page
You can also link to a specific section on a different page.
Example:
<a href="about.html#team">Meet Our Team</a>
This will open about.html
and scroll directly to the section with id="team"
.
Best Practices
- Use unique
id
values (no duplicates). - Choose descriptive names (e.g.,
id="contact-us"
instead ofid="sec1"
). - Avoid spaces in
id
names (use hyphens or underscores). - Great for accessibility and SEO (Google can identify section jumps).
FAQs
Q1. Can I use the same id
for multiple sections?
❌ No. Each id
must be unique in an HTML page.
Q2. What characters are allowed in id
?
Use letters, numbers, hyphens (-), underscores (_), and periods (.).
Avoid spaces.
Q3. Does linking with #anchor
affect SEO?
Yes, positively. Google recognizes #anchors
and can show “jump to section” links in search results.
Q4. What if the element with that id
doesn’t exist?
The browser won’t scroll and the link will do nothing.
Q5. Can I style sections differently when linked via #anchor
?
Yes, with CSS :target selector.