How to Link to a Section on the Same Page in HTML
To link to a section on the same page in HTML, use an
<a> tag with the href attribute set to the section's id preceded by a hash (#). For example, <a href="#section1">Go to Section 1</a> links to <div id="section1">.Syntax
Use an <a> tag with href="#sectionID" where sectionID matches the id of the target element. The target element must have an id attribute.
<a href="#section1">: Link that jumps to the element withid="section1".<div id="section1">: The target section with the matchingid.
html
<a href="#section1">Go to Section 1</a> <div id="section1">This is Section 1</div>
Output
A clickable link labeled 'Go to Section 1' that scrolls the page to the 'This is Section 1' text.
Example
This example shows a navigation link that jumps to a section below on the same page. Clicking the link scrolls the page smoothly to the target section.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Link to Section Example</title> <style> html { scroll-behavior: smooth; } section { margin-top: 100vh; padding: 2rem; background-color: #f0f0f0; border: 1px solid #ccc; } </style> </head> <body> <nav> <a href="#contact">Go to Contact Section</a> </nav> <section id="contact"> <h2>Contact Us</h2> <p>This is the contact section on the same page.</p> </section> </body> </html>
Output
A page with a link 'Go to Contact Section' at the top. Clicking it smoothly scrolls down to the 'Contact Us' section with heading and paragraph.
Common Pitfalls
- Forgetting to add the
idattribute to the target element means the link won't work. - Using spaces or special characters in
idvalues can cause issues; use simple, unique IDs. - Using the
nameattribute on anchors is legacy and not recommended. - Links with
href="#"without a valid target cause the page to jump to the top.
html
<!-- Wrong: Missing id --> <a href="#section2">Go to Section 2</a> <div>Section 2 content without id</div> <!-- Right: With id --> <a href="#section2">Go to Section 2</a> <div id="section2">Section 2 content with id</div>
Quick Reference
Remember these key points when linking to sections on the same page:
- Use
href="#sectionID"in the link. - Target element must have
id="sectionID". - Keep
idvalues simple and unique. - Use CSS
scroll-behavior: smooth;for smooth scrolling.
Key Takeaways
Use
href="#id" in links to jump to sections with matching id attributes.Always add a unique
id to the target element you want to link to.Avoid spaces and special characters in
id values for reliable linking.Use CSS
scroll-behavior: smooth; for a better user experience with smooth scrolling.Links without a valid target
id will not work and may jump to the top of the page.