How to create links to sections within the same page in HTML ?
In this article, we will see how to create “links” in their HTML page which are linked to the section of the same page. In order to achieve this, we need to have some prior knowledge of some HTML features anchor tag with the “href” and class and id.
Approach: Since we now know that the anchor tag <a> is used for creating any link. we also know that “href” can hold the link address. But in our case, we want to link to the section of same page, in that case we will use id to identify different sections of our web page . These ids then can be passed to the href as shown below:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
<a href="#section1" >section 1</a>
In this case, the id “section1” can be given to any component or section of our web page. The above link will point to the section that has the id section1. Here href attribute knows that the “section1” is not an ordinary link rather it is an id by providing “#” in the beginning. it is also obvious that we should not use class names in the href attribute as they are not understood by the href attribute. Also, the class names are not unique in the document so it does not make sense to use them as an identifier to a particular section.
Example: In this example, we are dividing our web page into different sections using div, The first section has class “nav”. we can see that this section has <a> tags to navigate to different sections of our page. Then we have four sections, each is uniquely identified with the ids such as “section1″,”section2” and so on. This ids are given to the href of the <a> tags in the navigation section. whenever the user clicks on the <a> tag,it links the user to the particular section.
Below is the implementation of the above approach: