How to Add a Class or ID to an Anchor Tag in HTML


In this article, we will go over how you can add a class or ID to an anchor tag in HTML, so that we can style different anchor tags differently if you wanted to with CSS.

So that you can see for yourself and visualize why you would do this, let's go over an example.

Let's say you have an anchor tag such as the one shown below:

This is one example of an anchor tag

You can see that this anchor tag is the standard blue color underlined. When we hover over it, it turns to an orange color.

Let's say we wanted to display certain anchor tags, or links, on a web page this way.

But other anchor tags, we want to show differently. Instead of being blue and underlined, we want them to be maroon without any underlinings, and yellow when we hover over it, such as the link shown below:

This is another example of an anchor tag

You can see now how this one is styled so differently that it produces an anchor tag with a different color, is not underlined, and changes to yellow when hovered over.


In order to style an anchor, we have to give it a class (and assign a name to that class), using the following format:

where href is assigned the place on the web where you want to direct the user, newanchor is the name of the class we assign that anchor tag to, and Text to be shown on screen is the text of the anchor tag that is visible to the user and that gets clicked.

Here, href is assigned to a #(hash symbol), because we're using the a tag, just for styling purposes, not actually to redirect users to a place on the web.

Now that we assigned the anchor tag to the class named newanchor, let's go over how we would style this in CSS to produce the effect shown above.

CSS Code

We would add the following lines of code to the CSS file:

The above is the CSS code to style our anchor tag assigned to the newanchor class. The above code makes the link a maroon color, gives it no underlining, and gives a yellow color when hovered over with a mouse.

In order to style any of the 4 special attributes of an anchor tag with the name classname, the following CSS would be added to the anchor tag:

The link attribute changes the color of the link. The visited attribute changes the color of the link once you user has clicked on it (and visited the site). The hover attribute changes the color of the link when a user hovers over it. The active link changes the color of the link the moment it is clicked by a user. This is the color which the link will change to at the moment it is clicked.

In our example, since our anchor tag was assigned the name newanchor, the lines of code in CSS would be:

Even though .newanchor:link is one way to change the color of the link, another shorthand way of doing it is simply just stating .newanchor {} to change the color.

So these lines of code:

Would be the same as: