Free HTML tutorial

HTML IDs and Page Anchors

An id identifies one element on a page. Use unique id values to target an element or create a link directly to a section.

Assign a unique ID

<h2 id="contact">Contact</h2>

In CSS, target the element with a hash selector:

#contact {
  scroll-margin-top: 6rem;
}

Link to a section

<a href="#contact">Go to contact information</a>

IDs should be unique within a document. If you want to style many elements the same way, use a class instead.

Use one ID for CSS and JavaScript

The same id can be read by CSS and JavaScript. For example, an element with id="contact" can be selected in CSS with #contact or in JavaScript with document.getElementById("contact").

<h2 id="contact">Contact</h2>

<style>
  #contact {
    scroll-margin-top: 6rem;
  }
</style>

<script>
  const section = document.getElementById("contact");
</script>

Link to an ID on another page

Add the target page’s file path before the fragment. The browser opens that page and jumps to the element whose ID matches the fragment:

<a href="about.htm#contact">Contact the team</a>

Use a short, descriptive ID without spaces, and make sure the value is unique on that page. IDs work well for specific targets; use a class when several elements need the same styling or behavior.

HTML ID questions

Can two elements use the same ID?

No. An ID is meant to identify one element in a document. Reusing it can make links and scripts target an unexpected element. Use a class for a group of elements instead.

How do I link to a section on the same page?

Give the target element an ID such as contact, then link to it with href="#contact".