The :target pseudo class

The :target pseudo-class is a powerful CSS selector that allows you to style elements on your webpage based on whether they are the target of a fragment identifier. In other words, it allows you to style an element when it is being linked to by an anchor link on the same page. In this blog post, we’ll take a closer look at the :target pseudo-class and show you how to use it to enhance the user experience on your website.

When an anchor link is clicked, the browser will navigate to the linked element on the page, and the fragment identifier (the part of the URL after the “#” symbol) will match the ID of the linked element. The :target pseudo-class allows you to style the element that is being linked to based on this fragment identifier match.

Example of using :target

For example, let’s say you have a webpage with a table of contents, and you want to highlight the section of the page that the user is currently viewing. You can use the :target pseudo-class to apply a different background colour to the linked element when it is being viewed.

:target {
    background-color: #f0f0f0;
}

You can also use the :target pseudo-class to reveal or hide elements on the page based on whether they are the target of a link. For example, you could use it to show or hide a section of text, or to reveal a drop-down menu when a certain link is clicked.

/* Hide the element with the ID "hidden-content" by default */
#hidden-content {
    display: none;
}

/* Show the element with the ID "hidden-content" when it is the target of a link */
:target #hidden-content {
    display: block;
}

The :target pseudo-class can also be used in combination with other selectors to create more advanced effects. For example, you could use it to change the colour of a link when the linked element is being viewed.

/* Change the color of the link when the linked element is being viewed */
a:target {
    color: red;
}

It’s important to note that the :target pseudo-class only applies to elements that are on the same page as the link. If the link is pointing to a different page, the :target pseudo-class will not apply.

Conclusion

In conclusion, the :target pseudo-class is a powerful CSS selector that allows you to style elements on your webpage based on whether they are the target of a fragment identifier. It can be used to enhance the user experience on your website by providing visual cues to the user about where they are on the page, or by revealing or hiding elements based on user interactions. With a little creativity, the possibilities are endless!

Facebook Comments