By Guy Routledge

AtoZ CSS Quick Tip: When to Use the ID Selector Code

By Guy Routledge

This article is a part of our AtoZ CSS Series. You can find other entries to the series here.
View the full screencast and transcript for id Selector here.

Welcome to our AtoZ CSS series! In this series, I’ll be exploring different CSS values (and properties) each beginning with a different letter of the alphabet. We know that sometimes screencasts are just not enough, in this article I’ve added a new quick tip/lesson about the id Selector for you.


I is for id Selector

In the video for letter I, we looked at the id selector and how it factors into CSS. I also had a good rant about the issues with using id over class, both in terms of reusability and specificity.

To balance the argument a little I should talk about when we should use ID and why.

To provide a unique hook for Javascript

This is a little outside the normal scope of CSS (although not if you believe the constant debate of whether or not we need CSS anymore) it’s a useful piece of advice none the less. The fastest and most direct way of interacting with an element with JavaScript is to target it by its id attribute.

To provide targeted anchor tags for navigation

ID’s can be used on a single page for navigation by setting the href in an anchor tag to the id. Check out this example that allows you to navigate easily to different chapters on the page.

See the Pen ORyGLa by SitePoint (@SitePoint) on CodePen.

For linking form inputs with their labels

When building forms, we can link the label of a particular input by the for attribute on the label with the corresponding id attribute of the input. This means that clicking on the label will focus a text input field or toggle the state of checkboxes or radio buttons.

And, finally, here’s one last tip about using ID’s: a valid id cannot start with a number and must be at least one character long.

  • can we slowly focus on div with ID.?
    Thanks Bruce Mesnekoff

  • Tracy-Gregory Gilmore

    Having a firm understanding of the Specificity rules is vital for anyone writing/maintaining CSS. Your explanation was very well done and I full support you policy of “Least Specificity”. A mention about the restrictive use of the !important operator would not have been out of place.

Get the latest in Front-end, once a week, for free.